Reputation: 6264
I have a problem of finding when all the ajax completed.Here is my function.
function getValuesForTablePropertySelected(questionList, itemsArray) {
for (var i = 0; i < itemsArray.length; i++) {
switch (itemsArray[i]) {
case "Tags":
loadTag(questionList);
break;
case "Date Created":
displayTablePropertySelected(itemsArray);
break;
case "Date Last Used":
loadDLU(questionList);
break;
case "Number of Launched Surveys Used In":
loadNLSU(questionList);
break;
case "Number of Reponses":
loadNR(questionList);
break;
case "Type 1 Associations":
loadT1A(questionList);
break;
case "Type 3 Associations":
loadT3A(questionList);
break;
case "Sites Linked To":
loadSLT(questionList);
break;
case "Last Modified By":
displayTablePropertySelected(itemsArray)
break;
default:
break;
}
}
showResult();
}
Each function in the "CASE" contains an ajax call. I need to use asynchronous calls only.
I want to trigger "showResult()" function after AJAX complete in all the functions . Different AJAX is taking different time to complete.
Please help me find a solution for this situation.
Upvotes: 0
Views: 183
Reputation: 4288
You can do it easily with jQuery .ajaxComplete()
:
// create a counter (global)
var ajax_calls_counter = 0;
// in your current code, in each ajax call success, add 1 to the counter
// manage ajax succeeded events
$(document).ajaxComplete(function(){
if( ajax_calls_counter == itemsArray.length ){
showResult();
}
});
An example (jsFiddle):
$(function(){
$(this).ajaxComplete(function(){
var $body = $('body');
$body.append('ajax number '+ counter +' call complete!<br />');
if( counter == array.length ) $body.append('<strong>all</strong> ajax calls completed');
});
var array = [1, 2, 3, 4, 5];
var counter = 0;
for( var i = 0; i < array.length; i++ ){
$.ajax({
url: location.href,
success: function(){
counter++;
}
});
}
});
Upvotes: 3
Reputation: 330
For a single AJAX call . You can write the code in the success block . But if you want to check status for multiple AJAX calls better you use some variable which you set after every success/failure you receive from the AJAX call.
And if you receive the expected variable value then perform the desired action
Upvotes: 0