1

I'm trying to loop an ajax request for 10 times. I've noticed some weird errors, such as int being 10, 10 times. I've searched and found it's related to AJAX async. I want to have something that waits until the ajax request is finished and then continues.

Thanks in advance.

do{
    var int=0;
    $.ajax({...},
        success:function(response){ int++; },
    });
    alert(int);
}while(int<10);
MJW
  • 31
  • 1
  • 8
  • would moving the alert into the success function fit the behavior you want? – spaniol6 Dec 04 '15 at 21:13
  • ajax by definition is async. making it wait defeats it's purpose. jquery when is a better option. http://api.jquery.com/jQuery.when/ – anu Dec 04 '15 at 21:16
  • 1
    @anu ajax is not always async. Yes, it is the main usage of ajax to be async, but you can still put `async: false` in your ajax requests. – Andy Guibert Dec 05 '15 at 00:19

3 Answers3

3

If your success handler is referring to int, then yes, by the time it runs int will always be 0, since that's long after the loop has completed.

If you really want the calls to run in succession, with a different value each time, move the call to a function, and call it as needed from the ajax success handler:

function myAjax(int) {
  if (int >= 10)
    return;

  $.ajax({   //...
     success:function(response){ 
       int++;
       // whatever we need to do with int and the response

       myAjax(int);
     }
  });
}

myAjax(0);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
1

You can set parameter async: false to ajax object.

$.ajax({
        url: $(this).attr('href'),
        type: 'GET',
        async: false,
        error: function(){
            return true;
        },
        success: function(msg){
        }
    });
Maxim Goncharuk
  • 1,285
  • 12
  • 20
0

I believe this is the code you are looking for:

for (var int = 0; int < 10; int++) {
    (function (int) {
        $.ajax({
            url : 'process.php',
            success : function() {
                alert("TEST");
            }
        });
    })(int);
}

Here are some links with more information on how this works: jQuery AJAX calls in for loop [duplicate] JavaScript closure inside loops – simple practical example

Community
  • 1
  • 1
David
  • 429
  • 2
  • 5
  • 14