views:

78

answers:

2

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

my question is : How can i force it to wait and not continue until we get all the call backs from the ajax requests ?

Thanks!

+2  A: 

you can use sucess (ie a callback function of ajax jquery) like below :

$.ajax({
  url: url,
 dataType: 'json',
 data: data,
 success: function(data){
 //Write your code here.
    }
});

You can get documentation of ajax below -

ajax

Alpesh
how can i use it in my code ?
Haim Evgi
@Haim Evgi: Move the code you have after the call and you want to execute after the call finished inside the callback.
Felix Kling
I have edited my code as per your requirement. You can use ajax instead of getjson as described above.
Alpesh
thank you very much , but i use @shay solution
Haim Evgi
+2  A: 

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:

for (j=1; j <= 7; j++){
  (function(index) {
    $.getJSON('my.php', {id:index}, 
      function(data) {
         $.each(data, function(index2, array){
         ........
         }); 

         if (j === 7) {
            initDoneDoMoreStuff()
         }
      });
    })(j)
} 

or trigger:

for (j=1; j <= 7; j++){
  (function(index) {
    $.getJSON('my.php', {id:index}, 
      function(data) {
         $.each(data, function(index2, array){
         ........
         }); 

         if (j === 7) {
            $(document).trigger("initdone");
         }
      });
    })(j)
}

$(document).bind("initdone", function() {....});
Shay Erlichmen