4

I have a jQuery ajax call in a loop. However I do not want those ajax calls to be made simultaneously, I need the first ajax call to finish before going on to the next.

for (var i = 0; i < options.length; i++) {  
        jQuery.ajax({
            url: "ajax_file.php",
            data: //some data based on DOM tree
            success: function(data){
                //some DOM manipulation
            }
        });
}

I want the loop to continue executing only after the DOM manipulation in SUCCESS was executed (because the ajax call depends on the DOM tree). In theory I know I could set the ajax call to be async:false, but it is not recommended as it can freeze the browser.

3 Answers 3

8

Because async: false is always a bad idea, I'd recommend something like this:

var recur_loop = function(i) {
    var num = i || 0; // uses i if it's set, otherwise uses 0

    if(num < options.length) {
        jQuery.ajax({
            url: "ajax_file.php",
            data: //some data based on DOM tree
            success: function(data){
                recur_loop(num+1);
            }
        });
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

that looks like some weird recursion ... but seems to works like a charm so far!
Great solution which I was looking for! Thanks for saving my life.
1

Setting async to false will do that. Keep in mind that the web browser might lock up while the requests happen if you do them asynchronously.

jQuery.ajax({
    async : false,
    url: "ajax_file.php",
    data: //some data based on DOM tree
    success: function(data){
        //some DOM manipulation
    }
});

Comments

1

you can do something like this (pseudo-code):

var i =0;
doLoop();

function doLoop() {
   //exit condition
   if (i >= options.length) {
      return;
   }
   //loop body- call ajax
   $.ajax({
   //...
   success: function(data) {
      //do your thing
      i++;
      //go to next iteration of the loop
      doLoop();
   }
   });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.