How to know when all ajax calls are complete
The easy way
The easiest way is to use the .ajaxStop()
event handler:
$(document).ajaxStop(function() {
// place code to be executed on completion of last outstanding ajax call here
});
The hard way
You can also manually detect if any ajax call is still active:
Create a variable containing number of active Ajax connections:
var activeAjaxConnections = 0;
just before opening new Ajax connection increment that variable
$.ajax({
beforeSend: function(xhr) {
activeAjaxConnections++;
},
url (...)
in success
part check if that variable equals to zero (if so, the last connection has finished)
success: function(html){
activeAjaxConnections--;
$('#result_'+rowNum).empty().append(html);
$('#coda_'+rowNum).removeClass("loading");
$('#coda_'+rowNum).addClass("loader");
if (0 == activeAjaxConnections) {
// this was the last Ajax connection, do the thing
}
},
error: function(xhr, errDesc, exception) {
activeAjaxConnections--;
if (0 == activeAjaxConnections) {
// this was the last Ajax connection, do the thing
}
}
As you can see, I've added also checking for return with error
A neat solution would be to use;
$("body").ajaxStop(function() {
//Your code
});
For more information check out the jQuery .ajaxStop function at http://api.jquery.com/ajaxStop/
Maybe:
jQuery.active == 0
Stolen from:
http://artsy.github.com/blog/2012/02/03/reliably-testing-asynchronous-ui-w-slash-rspec-and-capybara/
More info on StackOverflow:
jQuery.active function