I have multiple ajax queries running at the same time, and I want them to wait for the last one to return, and then run the success handler on all of the ajax calls. For a
This can probably be done in a very similar fashion to what you've already proposed.
First, create global variables var sleep = true
and var request_count = 0
. Then start a timer that checks request_count
against total number of requests every second or so. Then, your success functions can increment request_counter
and then start looping until sleep == false
. Then, when the monitoring function running via timer detects request_count == TOTAL_REQUESTS
it sets sleep = false
, and all your success functions continue about their business at that point.
Use the jQuery $.when() function to run something when all the ajax calls finish:
jQuery.when docs
var async1 = $.ajax({//ajax call 1
url:page1.php,
success: function(data1){
//do something with data1
}
});
....
var async2 = $.ajax({//ajax call 2
url:page2.php,
success: function(data2){
//do something with data2
}
});
$.when(async2, async1).done(function(result2, result1) {
... do this when both are successful ...
});
Added in response to questions:
If you have a bunch of ajax calls you can use 'apply' like this:
var results = [];
results.push(async1);
results.push(async2);
... for all the results ...
$.when.apply(this, results).done(function() {
... use 'arguments' array to get results ...
});
A simple solution will be to use PreloaderQ module
https://www.npmjs.com/package/preloaderq
Use as below
var preloader = new PreloaderQ()
preloader.setEmptyCallback(function(){
//all tasks are finished
})
preloader.setFirstTaskCallback(function(){
//started first task
})
preloader.enqueueTask('ajax1')
$.ajax({//ajax call 1
url:page1.php,
success: function(data1){
prealoader.dequeueTask('ajax1')
//do something with data1
}
});
preloader.enqueueTask('ajax2')
$.ajax({//ajax call 1
url:page2.php,
success: function(data2){
prealoader.dequeueTask('ajax2')
//do something with data2
}
});
The emptycallback will be called after both are finished