Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control a request when a jQuery Ajax call done

I'm using $.post() to call a server using Ajax and then using the JTemplate to write data to the current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the div element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed.

How can I manage a redirect directive from an Ajax call with jQuery 1.9?

like image 448
nnnnMM Avatar asked Nov 08 '22 19:11

nnnnMM


1 Answers

You must use json data to response to client. For example: In PHP file

<?php
//for example, data you want to response to client is a html string
$data = '<table></table>';
if($is_timeout && $is_ajax_request) {
   //shouldn't redirect, should return json_encode
   echo json_encode(array('timeout'=>1));
   die();
}else{
   echo json_encode(array('data'=>$data));
   die();
}

And in your javascript post you can edit below:

$.post('your_url_to_php_file',{data:data_to_post}, function(resp){
   var data = jQuery.parseJSON(resp);
   if(data.timeout) {
      alert("timeout");
      return;
   }else{
      $("#your_div").html(data.data);
   }
})
like image 78
Kelvin Avatar answered Nov 14 '22 22:11

Kelvin