This question already has an answer here:
I have some ajax calls in my document.ready()
like :
for (j=1; j <= 7; j++){
(function(index) {
$.getJSON('my.php', {id:index},
function(data) {
$.each(data, function(index2, array){
........
});
});
})(j)
}
//DO NOT CONTINUE UNTIL FINISH AJAX CALLS
........
MORE JQUERY CODE
How can i force it to wait and not continue until we get all the call backs from the ajax requests ?
I do not like any answer at all, the best way (since Jquery 1.5+) is to use Deferred objects, those are objects to manipulate async calls, you can solve :
This way myFunc executes after the 2 ajax calls are made, and myFailure if either one has an error.
You can read more about it in the jquery official documentation:
JQuery Deferred Object
I write this solution if anyone sees this post it may be helpful.
Sorry my english :P
First off, you might want to consider doing the startup code in a single call.
Second: Instead of waiting just call another function call. for the above code it should look something like:
or trigger:
you can use sucess (ie a callback function of ajax jquery) like below :
You can get documentation of ajax below -
ajax
It wasn´t easy for me to do it, but maybe you find my code useful. It´s a process to submit all forms in the dom and after all of them are stored, redirect the user to another page.
The problem with something like if (j == 7) is the situation when the 7th request is very very fast, and even one of the others is slow. Even though you have queued it up last, it might not be the last to complete.
This answer seems to work for all conditions: https://stackoverflow.com/a/3709809/813154