Jquery – Multiple ajax call handling


I am using jQuery to make some ajax calls and wonder how people handle this situation.

  1. An ajax request is made to the server to retrieve some info.
  2. Before the request returns another request is made. The first request is now invalid and out of date.

How do I tell that the initial request is now invalid and can be ignored when it returns. I only want to display the results of the second request and ignore (or cancel) the first.

Best Solution

jQuery returns the XmlHttpRequest object from the call to ajax(), which I've used to achieve what you desire as follows:

var lastRequest;
function getSomeData() {
    if(lastRequest) {
        lastRequest = null
    lastRequest = $.ajax(...);

The net effect is that earlier requests' responses are ignored if a subsequent request is made.