Queuing Ajax Requests - J Query

You want to have greater control over the order of many separate Ajax requests.


This recipe illustrates two different ways to queue Ajax requests. The first fills a queue with requests, sending subsequent requests once the previous request has returned a response. The second sends groups of requests in parallel. But, it doesn’t execute the callback functions for each request until all responses have returned. An example of normal un queued requests is included for comparison:

The ajaxqueue jQuery plugin (available at http://plugins.jquery.com/project/ajaxqueue/) is used for queuing behaviors. Three buttons trigger each set of Ajax requests. A log of the responses is displayed in a paragraph element:

The first button triggers normal Ajax requests. Ten requests are sent, each with a number for their position in the sequence. The server.php script simulates a server under load by sleeping random amounts of time before returning a response. When it arrives,the response is appended to the contents of the #response paragraph:

The “Queued requests” button adds each request to a queue by calling the ajaxQueue() function. Internally, the ajax() function is called with the provided options, each time a request is de queued. After each of the requests has added to the queue, a call to dequeue() with the ajaxQueue function as a parameter triggers the first request. Each subsequent request will be sent in turn:

The final set of requests use the ajaxSync() function to send the requests in parallel but synchronize the execution of the provided callbacks when the responses return.

Responses from the un queued requests come back out of order. This behavior is not necessarily undesirable and in many cases may be preferred. However, there are scenarios where one would like more control over Ajax requests and their responses. The functionality provided in ajaxQueue() suits the case where each subsequent request is dependent upon the response to the previous request, whereas ajaxSync() supports the use case of manipulating data, which is gathered from a variety of servers. In this scenario, processing is unable to commence until all servers have returned a response and the complete set of data is present.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics