0

I have a loop that fires off AJAX requests, is it possible to pause the loop until the AJAX has returned for each iteration?

 for (var i = 0; i < 5; i++) {

     var data = "i=" + 1;
     var ajax = $.ajax({
         url: '/ajax.php',
         type: 'post',
         data: data,
         success: function(result)
         {
           //alert(result);
         }                                                      
     });

     //pause the for loop here

     ajax1.done(function (result) {
         //continue the for loop
     }); 
 }
1
  • why are you using it in loop Commented May 25, 2018 at 10:44

2 Answers 2

1

You want the Ajax calls to be asynchronous but also execute successively. Instead of a for loop, you can use recursion.

doAjax (index, maxNumber) {

     var data = "i=" + index;
     var ajax = $.ajax({
         url: '/ajax.php',
         type: 'post',
         data: data,
         success: function(result)
         {
           //alert(result);
         }                                                      
     });
     ajax1.done(function (result) {
         if(index<=maxNumber){
               doAjax(index + 1, maxNumber);
     });
}

You can call this as doAjax(1, 5) which will make all ajax calls from 1 to 5 after the previous one is over.

Sign up to request clarification or add additional context in comments.

Comments

0

In ES6 you can probably use the async / await syntax:

for (let i = 0; i < 5; i++) {
  let data = "i=" + i;
  let result = await $.ajax({
    url: '/ajax.php',
    type: 'post',
    data: data
  });
  console.log(result);
}

(This needs to be done in a async function though.)

Other than that there is no syntax in JS that would allow this, so you have to adapt your code:

function requestRange(start, end) {
  function request(i) {
    if (i >= end) return;
    let data = "i=" + i;
    let ajax = $.ajax({
      url: '/ajax.php',
      type: 'post',
      data: data
    });
    ajax.done(function (result) {
      console.log(result);
      request(i + 1);
    }); 
  }
  request(start);
}

requestRange(0, 5);

1 Comment

The ajax functions already return a Promise/A+ compatible promise for jQuery 3.x . So using let data = await $.ajax( would already work.

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.