53

I am new to Ajax and I am attempting to use Ajax while using a for loop. After the Ajax call I am running a function that uses the variables created in the Ajax call. The function only executes two times. I think that the Ajax call may not have enough time to make the call before the loop starts over. Is there a way to confirm the Ajax call before running the function printWithAjax()? I do not want the printWithAjax() function to execute until the Ajax call is complete. Any help will be greatly appreciated.

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
         url: 'api.php',                        
         data: 'id1='+q+'',                                                         
         dataType: 'json',
         async:false,                    
         success: function(data)          
         {   
            id = data[0];              
            vname = data[1];
         }
      });

       printWithAjax(); 

 }//end of the for statement
}//end of ajax call function
Geo
  • 3,160
  • 6
  • 41
  • 82
stat8
  • 689
  • 1
  • 6
  • 10
  • 2
    since you are using `asycn:false`(**don't ever use it, if possible**), the print will execute only after the ajax is completed.... – Arun P Johny Apr 25 '14 at 02:43
  • but the correct solution will be is to call the print function within the success callback and pass the id and vname as arguments – Arun P Johny Apr 25 '14 at 02:44
  • So you want printWithAjax to fire once for each ajax call? – kempchee Apr 25 '14 at 02:44
  • 1
    like http://jsfiddle.net/arunpjohny/yA8Zu/2/ - do you also want to make sure the ajax request is executed in sequence if not you can remove the `async:false` – Arun P Johny Apr 25 '14 at 02:45
  • 2
    Since your just passing numbers 1 - 10, why not pass an array or range (1-10) to your server and just make one ajax call? Rather then making 10 ajax requests. Also you can loop through the data to control its display. – Jay Bhatt Apr 25 '14 at 02:51
  • Thank you all for your quick help! I have tried each scenario and I am now able to complete more loops. However, it does not finish all 10. I think the correct way to complete this project may be to attempt to use an array as described by Jay. – stat8 Apr 25 '14 at 03:22
  • You can use "complete" event for that. https://api.jquery.com/Ajax_Events/ – Hiren Patel Jul 17 '21 at 06:07

6 Answers6

75

Try this code:

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
     url: 'api.php',                        
     data: 'id1='+q+'',                                                         
     dataType: 'json',
     async:false,                    
     success: function(data)          
     {   
        id = data[0];              
        vname = data[1];
     },
    complete: function (data) {
      printWithAjax(); 
     }
    });

  }//end of the for statement
  }//end of ajax call function

The "complete" function executes only after the "success" of ajax. So try to call the printWithAjax() on "complete". This should work for you.

Naveen Chandra Tiwari
  • 5,055
  • 3
  • 20
  • 26
44

You can use .ajaxStop() or .ajaxComplete()

.ajaxComplete() fires after completion of each AJAX request on your page.

$( document ).ajaxComplete(function() {
  yourFunction();
});

.ajaxStop() fires after completion of all AJAX requests on your page.

$( document ).ajaxStop(function() {
  yourFunction();
});
Mukesh Chapagain
  • 25,063
  • 15
  • 119
  • 120
17

Add .done() to your function

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
         url: 'api.php',                        
         data: 'id1='+q+'',                                                         
         dataType: 'json',
         async:false,                    
         success: function(data)          
         {   
            id = data[0];              
            vname = data[1];
         }
      }).done(function(){
           printWithAjax(); 
      });



 }//end of the for statement
}//end of ajax call function
Geo
  • 3,160
  • 6
  • 41
  • 82
  • 6
    done is the same as `success`. you want `".always()"` – Michel Ayres Aug 15 '14 at 13:40
  • @MichelAyres I thought success will run only if it is successful and done would run no matter what... – Geo Aug 19 '14 at 16:26
  • `run no matter what` == `.always()` take a look at [jQuery.ajax handling continue responses: “success:” vs “.done”?](http://stackoverflow.com/questions/8840257/jquery-ajax-handling-continue-responses-success-vs-done) also ["An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success()"](http://api.jquery.com/jquery.ajax/) – Michel Ayres Aug 19 '14 at 16:52
1

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

Ryan Smith
  • 704
  • 2
  • 6
  • 13
0

You should set async = false in head. Use post/get instead of ajax.

jQuery.ajaxSetup({ async: false });

    $.post({
        url: 'api.php',
        data: 'id1=' + q + '',
        dataType: 'json',
        success: function (data) {

            id = data[0];
            vname = data[1];

        }
    });
Phong Ca
  • 17
  • 2
0

try

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({  

 url: 'api.php',                        
 data: 'id1='+q+'',                                                         
 dataType: 'json',
 success: function(data)          
  {

    id = data[0];              
   vname = data[1];
   printWithAjax();
}
      });



}//end of the for statement
  }//end of ajax call function