MJW
MJW

Reputation: 31

Do While Loop for AJAX?

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);

Upvotes: 1

Views: 4142

Answers (3)

David
David

Reputation: 439

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

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

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);

Upvotes: 3

Maxim Goncharuk
Maxim Goncharuk

Reputation: 1333

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){
        }
    });

Upvotes: 1

Related Questions