$.ajaxchain

Chains AJAX requests. $.ajax fetches a single page, like this:

$.ajax({
  url: "formhandler", // Fetch "formhandler" URL
  data: { _offset: 0 }, //    with ?_offset=0
});

$.ajaxchain keeps fetching more page using a chain: function.

var ajaxchain_instance = $.ajaxchain({
  url: 'formhandler',                           // Fetch "formhandler" URL
  data: {_offset: 0, _limit: 10},               //    with ?_offset=0&_limit=10
  chain: function(response, request) {          // When the response is retrieved
    if (response.length > 0)                    //    if the response is non-empty
      return {data: {_offset: request.data._offset + 10}    //    fetch the next page
  },
  limit: 10,                                    // Get at most 10 pages (default)
  // any other $.ajax options can be passed
})

The flow when $.ajaxchain(request) is called is:

  1. Fetch URL using $.ajax using the request options
  2. If the page limit is not reached, call the .chain(response, request, xhr) function.
    • request is the request sent to $.ajax
    • response is the response from $.ajax
    • xhr is the jqXHR object
  3. If .chain() returns a non-empty object
    • update the request with the response of .chain()
    • call $.ajaxchain(request) with the new request
    • Otherwise, stop.

$.ajaxchain options

$.ajaxchain() accepts the same options as $.ajax with a few additional options:

The chain: function can be used with FormHandler.

  chain: function(response, request) {
    if (response.length > 0)                              // If the response is not empty
      return {data: {_offset: request.data._offset + 10}}   // Fetch the next page
  }

You can use a set of pre-defined helper functions for chaining:

You can also construct your own chain: functions. For example:

On YouTube:

  chain: function(response, request) {
    if (response.nextPageToken)
      return {data: {pageToken: response.textPageToken}}
  }

If the results are at /page/1, /page/2, etc:

  url: `/page/1`,
  chain: function(response, request) {
    if (response.length > 0)
      return {url: `/page/` + (+request.url.split('/')[-1] + 1)}
  }

$.ajaxchain events

To access the response, we can use the ajaxchain_instance events. There are 3 events:

For example:

ajaxchain_instance
  .on("done", function (e) {
    // Called after ALL pages are loaded, or on error
    // Responses are in e.response[0], e.response[1], etc
    // Requests  are in e.request[0],  e.request[1],  etc
  })
  .on("load", function (e) {
    // Called when each page is loaded
    // e.response has the response
    // e.request  has the request
  })
  .on("error", function (e) {
    // Called when there's an error
    // e.request  has the request
    // e.exception is set if the .change() function threw an exception
  });