Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery : wait until all ajax calls finish then continue [duplicate]

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 ?

like image 478
Haim Evgi Avatar asked Oct 17 '10 07:10

Haim Evgi


People also ask

How do I make jQuery wait for an Ajax call to finish before it returns?

If you don't want the $. ajax() function to return immediately, set the async option to false : $(". my_link").

Can we execute run multiple Ajax requests simultaneously in jQuery?

There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed.

How wait until Ajax is done?

Your answer You may need to run certain code only after all Ajax requests have completed when working with many Ajax requests. To do this, use the when function in jQuery. It takes any number of arguments and executes once all of the parameter functions have been performed.


1 Answers

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 :

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);

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

like image 124
sandino Avatar answered Nov 10 '22 12:11

sandino