0

I have a loop and I want it to run when ajax ends everytime in the loop.
Is that possible?

for (var i=1;i<20;i++){
if (keepruning = 1) {
keepruning = 0;

$.post( "getname.php", { id: myarr[i] } ) .done(function( data ) { keepruning = 1 });

}

This is as close as I got... and this doesn't work.
Any help would be very much appriciated;

Nir Tzezana
  • 2,275
  • 3
  • 33
  • 56

4 Answers4

3

jQuery ajax is {async:true} by default so request dose previous request response you should use $.ajax({...}) instead of $.post so you can add {async:false} in parameters Like

$.ajax({
   url : "xyz.php", 
   async : false,
   dataType : json
   success : function(data){
           //code here
   }
});

You can also add {async:false} globally.

NOTE: This will work with all ajax function that define on page

$.ajaxSetup({async:false});
Girish
  • 11,907
  • 3
  • 34
  • 51
  • 2
    Just a note that [it's extremely poor practice to set async false](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call/14220323#14220323) – megawac Apr 01 '14 at 13:34
1

To do it the way you are trying to do you need a recursive function, because by default $.post is async.

(function proceed(i) {
    $.post('getname.php', {id: myarr[i]}).done(function(data) {
        if (++i < 20) proceed(i);
    });
}(0));

But you should think before doing that. Wouldn't simple parallel requests solve the problem?

You could also make sync requests, but I don't recommend that.

megawac
  • 10,953
  • 5
  • 40
  • 61
vhtc
  • 790
  • 6
  • 12
0
for (var i=1;i<20;i++){
if (keepruning = 1) {
    keepruning = 0;

    $.ajax({
        url: "getname.php",
        type: "post",
        async: false,
        data:{ id: myarr[i] },
        success: function (data) {
            keepruning = 1;
        },
        error : function (data) {
            keepruning = 0;
        }
    });
}

}

This is one way, with sync ajax

Neta Meta
  • 4,001
  • 9
  • 42
  • 67
0

Using async : false freeze the browser, which is UX wise not a good solution. If it a prlbem for you, you can also use a self-calling function to do the loop :

loop(0)
function loop(i){
    $.post( "getname.php", { id: myarr[i] } ) .done(function(){
       if(i < 20) loop(i++)
    });
}
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75