Control request while making jQuery Ajax call

I use $.post()to call the server using Ajax and then using JTemplateto write data to the current page. However, if the session expires, the server sends a redirect directive to send the user to the login page. In this case, jQueryreplaces the element with the divcontents of the login page, forcing the user's eyes to witness a rare scene.

How can I control the call redirection directive Ajaxwith jQuery 1.9?

+4
source share
1 answer

You must use json data to respond to the client. For example: In a 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 postyou 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);
   }
})
+1
source

All Articles