Reputation: 437
I have 3 ajax calls on my page. Second ajax call will call on success of first and third ajax call will call on success of second. Each response returns multiple records so I have to make a while loop to go through each records and make corresponding AJAX call. I need to pass data from while loop to subsequent AJAX call.
I want to print the console like:
First
Second
Third
First
Second
Third
First
Second
Third
All Asyc Call complete
However, it is showing me
First
First
First
All Asyc Call complete
Second
Second
Second
Third
Third
Third
// First Ajax Call
$.ajax({
success: function(response1) {
while(response1.next()) {
console.log("First");
// Second Ajax Call
$.ajax({
success: function(response2){
while(response2.next()) {
console.log("Second");
// Third Ajax Call
$.ajax({
success: function(response3){
while(response3.next()) {
console.log("Third");
}
}
})
}
}
})
}
}
})
console.log("All Asyc call completes");
Upvotes: 1
Views: 506
Reputation: 4288
You can do something like this:
$(document).ajaxSuccess(function() {
if( ajax_sucess_counter == 3 ) alert('the 3 ajax calls are completed');
});
var ajax_sucess_counter = 0;
$.ajax({
//...
success: function(){
// ...
ajax_sucess_counter++;
}
});
Using deferred objects:
$.when( $.ajax('call1.php'), $.ajax('call2.php'), $.ajax('call3.php') ).done(function() {
alert('the 3 ajax calls are completed');
}});
You have all information and more examples at jQuery Docs.
Upvotes: 3