The .deferred , .when , .then solution mentioned in other answers is much more elegant, but it is also possible to write your own simple solution so that you can see how this can be done manually. You just set the counter for the number of ajax calls you have in flight, and in the success handler for each ajax call, you decrease the counter and start your action when the counter reaches zero.
function DoMyAjaxCalls(callbackWhenDone) { var numAjaxCalls = 3; // set timeout so we don't wait more than 10 seconds to fire the callback // even if ajax calls aren't done yet var timer = setTimeout(callbackWhenDone, 10*1000); function checkAjaxDone() { --numAjaxCalls; if (numAjaxCalls == 0) { clearTimeout(timer); callbackWhenDone(); } } // first ajax call $.ajax({ url: 'ajax/test1.html', success: function(data) { // write code to handle the success function checkAjaxDone(); }, error: checkAjaxDone }); // second ajax call $.ajax({ url: 'ajax/test2.html', success: function(data) { // write code to handle the success function checkAjaxDone(); }, error: checkAjaxDone }); // third ajax call $.ajax({ url: 'ajax/test3.html', success: function(data) { // write code to handle the success function checkAjaxDone(); }, error: checkAjaxDone }); }
source share