Rudi
Rudi

Reputation: 1587

use paging with ajax call in a while loop

In a javascript function I make a call to the server and get batches of 10 records back. I need to do this untill I've had all records.

To start I made a while loop where in the error callback of the ajax call I would end the while loop.

Halfway through I started to realize that that would not work, as the ajax call is async and I would thus fire loads of requests in the loop. I'm sure there is a standard pattern to do this but I don't know how.

How can I do the ajax call in a loop and perform it as long as the call is not returning an error? Pseudo code I was building:

var stillRecordsAvailable = true;

while (stillRecordsAvailable) {
  // get the next batch of records
  $.ajax({
    url: '/getrecords.json',
    data: {data_set_id: dataset.id},
    type: 'GET',
    success: function(data, textStatus, xhr) {
      // do something
    },
    error: function(xhr, textStatus, errorThrown) {
      // nothing left to do
      stillRecordsAvailable = false;
    }
  });

Thanks for pointing me in the right direction

Upvotes: 1

Views: 1947

Answers (1)

Nico Valencia
Nico Valencia

Reputation: 141

You'd probably want to just wrap the ajax call in a function that is called on the ajax success callback:

function getRecords(data, textStatus, xhr) {

  if (data) {}; // do something...

  $.ajax({
    url: '/getrecords.json',
     data: {data_set_id: dataset.id},
     type: 'GET',
     success: getRecords
  });

}

This will only work if your server/API returns an error when no more records exist; however, this may not be the best pattern. A more elegant way of tracking asynchronous event state is through a deferred/promise pattern. jQuery has a great implementation: http://api.jquery.com/category/deferred-object/

Upvotes: 5

Related Questions