Skip to content Skip to sidebar Skip to footer

Ajax Jquery Multiple Calls At The Same Time - Long Wait For Answer And Not Able To Cancel

My problem is as follows: On a page, I am doing multiple (6) ajax calls (via jQuery) to fetch some data at the same time (using php wrapper to fetch the data via the calls) The re

Solution 1:

That is due to the maximum number of connections of the browser to a single domain.

See Browserscope for mamimum per browser.

  • IE 8+9: 6 connections
  • IE 10: 8 connections
  • Chrome 26: 6 connections
  • Firefox 21: 6 connections

What you could do is collect all Defferred objects and cancel them when the use clicks on a link.

example:

// some ajax callsdoAjax({});
doAjax({});

var requests = [];

// helper function to perform and register callsfunctiondoAjax(options) {
    var jqXHR= $.ajax(options);
    requests.push(jqXHR);
    jqXHR.always(function(jqXHR) {
         var index = requests.indexOf(jqXHR);
         if (index!=-1) {
             requests.splice(index, 1);
         }
    });
}

// function to abort all calls// when your application has a router to provide navigation, this function// is typically called when you navigate to another pagefunctionabortAllPendingRequests() {
    var i;
    for (i=0; i<requests.length; i++) {
        var xhr = requests[i];
        // already finished calls (readyState 4) should not be abortedif (xhr.readyState != 4) {
            xhr.abort();
        }
    }
};

All is left is calling the abortAllPendingRequests function when the user tries to navigate to another page.

When you have some sort of router (e.g. Backbone.Router) you could call it there.

If your application does not have a router for navigating, but you make use of plain anchor links, you could add an onClick to the links which calls the abortAllPendingRequests function.

Post a Comment for "Ajax Jquery Multiple Calls At The Same Time - Long Wait For Answer And Not Able To Cancel"