Wednesday, October 30, 2013

handling ajax redirects or 302 requests

With XMLHttpRequest in JavaScript , basically there is no way to detect a redirect in an AJAX request. The browsers AJAX object invisibly follow the redirects and only gives the last response header with response data. So to handle AJAX redirects one should devise their own method. An ideal method would be to check for AJAX request from server and give a response accordingly instead of redirect header.

One could check for ajax request simply by checking the request headers. the sample code is given below:

if( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  echo "AJAX REQUEST DETECTED";
}

Now you can simply echo the redirect url to your ajax response and redirect to that url from your browser. 

if( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$response = array('redirectUrl'=>'http://www.google.com');
  echo json_encode($response);
  exit();
}

From inside your JavaScript function you could parse the response and perform the action. 

In Codeigniter you can check for ajax request through 

$this->input->is_ajax_request();

In CakePHP :

$this->request->is('ajax')


Hope this helps!!! 

No comments:

Post a Comment