The easiest way to integrate Social Login in your React Apps ...Checkout NPM

Friday, June 7, 2013

Pending AJAX terminating on window.location.href issue

Consider following 2 lines executed together:
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!

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:
var timer = SetInterval(function(){
       window.location.href= 'Some Url';

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

What are your thoughts on this post? Did you like it?