tags:

views:

48

answers:

2

I'm using jquery and in one function I'm calling multiple function which are doing different ajax request for example

function contactForm(){
loadCountryList();
loadMyData();
checkUserType();

// doing my stuff

}

How can I know if all the ajax request are completed so that I start doing my stuff in the end? I don't want to call them one by one to minimize the request time. any suggestion will help me a lot.

+1  A: 

You can use the global ajax handlers here, specifically .ajaxStop(), like this:

$(document).ajaxStop(function() {
  alert("All requests have completed!");
  //if you don't want to run it again, for example on future requests
  //then just unbind it like any other event :)
  $(this).unbind('ajaxStop');
});

You can also use it directly on an element you want to show for example:

$("#successDiv").ajaxStop(function() {
  $(this).fadeIn();
});

The .ajaxStop() handler (it's just an event) runs when all requests finish, not after each one.

Nick Craver
@Sam - I need to wakeup, was pasting the wrong event name every time and didn't notice, thanks :) `.ajaxStop()` runs only once.
Nick Craver
ajaxStop is vulnerable to potential race conditions ... meaning, if you are waiting on 3 ajax requests, 1 returns and you never issued 2 you will get a stop .
Sam Saffron
@Sam - The AJAX requests are asynchronous, their success/complete handlers cannot run (including this event) until the current thread is finished, meaning if you're making the `$.ajax()` calls all together in the same thread, and the OP is, they **cannot** finish before the next starts, simply because JavaScript is single-threaded.
Nick Craver
@Nick, true, very good point, it still feels a bit risky since at some point you tend to add dependent calls sprinkle setTimeouts and so on, but for this trivial example you are right. +1
Sam Saffron
+1  A: 
// something like this

var countriesLoaded = false;
var dataLoaded = false; 
var userTypeChecked = false; 
var didRestOfStuff = false;

function readyForNextStage() {
  return countriesLoaded && dataLoaded && userTypeChecked;
}

// after you get a complete on each ajax callback 
countriesLoaded = true; // or dataLoaded and so on
if (readyForNextStage() && !didRestOfStuff) {
  didRestOfStuff = true;
  // do rest of stuff
}
Sam Saffron