Friday, 7 June 2013

Pending AJAX terminating on window.location.href issue

Consider following 2 lines executed together:

$.ajax('url',options)
window.location.href= 'some url';

Many browsers (Chrome for example) terminate Ajax request when they encounter redirect call.

Q. Why would I need ajax and redirect together?
A. There can be many reasons. Most important being tracking scripts which does analytic on page visits.

Q. Can't I solve that by making async as false for Ajax?
A. Definitely Yes!


$.ajax('url',{async:false})
would resolve the problem. But what if AJAX call is wrapped deep inside some third party plugin you're using where you've no control over ajax attributes? In this case you won't have the flexibility to apply async:false. To resolve this, you can make use of $.active property in JQuery. This property (damn useful) gives a count of number of open xmlHttpRequests on a page.

So, coming back to our problem, you can do following to ensure plugin's ajax executes before redirect:

SomPluginCalledHavingAjaxRequest()
var timer = SetInterval(function(){
if($.active==0){
clearInterval(timer);
window.location.href= 'Some Url';
}
},1000);

Here, every 1000ms we're checking if there is any open ajax request. The moment ajax from third party plugin is through, $.active will get 0 and control will fall under condition where we stop the interval and do the redirect.

No comments:

Post a Comment