0

I need to make ajax calls in a cycle making new call after the previous is finished.

for (var year = 2000; year <= 2017; year++) 
{ 
    $.ajax(
    {
        url: 'calendar.php?year=' + year,
        beforeSend: function()
        {
            console.log('Loading year: ' + year);
        },
        success: function(result)
        {
            $('#events').append(result);
        }
    });
}

But when I check the console all calls are made at the same time.

user229044
  • 232,980
  • 40
  • 330
  • 338
Koralek M.
  • 3,231
  • 4
  • 26
  • 32
  • 2
    That's because the `for` loop executes in a couple of milliseconds. If you want to delay the calls, use `setInterval()` or chained `setTimeout()` calls - although I'd suggest if possible making a single request to get data for all relevant years. Making 17 rapid AJAX requests to your server * the number of concurrent users you have isn't a great idea – Rory McCrossan Jul 20 '17 at 15:39

2 Answers2

2

You could use the Promise API of jQuery to chain up the requests. Whenever on request is finished the queryYears is called another time with the year incremented by one, until year is larger then maxYear

function queryYears(year, maxYear) {
  // check if the year is less or equal maxYear
  if (year <= maxYear) {
    return $.ajax({
        url: 'calendar.php?year=' + year,
        beforeSend: function() {
          console.log('Loading year: ' + year);
        }
      })
      .then(function(result) {
        $('#events').append(result);

        //incremenat year by one
        year++;

        //only call queryYears if year is less or equal to maxYear
        if (year <= maxYear) {
          return queryYears(year, maxYear);
        }
      })
  } else {
    // if not return a rejected Promise
    return Promise.reject(new Error(year + ' is larger then ' + mxYear))
  }
}



queryYears(2000, 2017)
.then(function() {
  console.log('finished')
})
.catch(function(err) {
   console.log('failed with: ')
   console.dir(err)
});
t.niese
  • 39,256
  • 9
  • 74
  • 101
0

A nasty way to do it could be to set your $ajax option async to false, however, this is not recommended, it can back up the browser and give the users a bad experience. Instead you could create an array of promises. This could help How to wait until jQuery ajax request finishes in a loop?

CumminUp07
  • 1,936
  • 1
  • 8
  • 21