Question

jQuery has some abort APIs which can be used to attempt an abort request. Can jQuery actually ever decide to abort an Ajax request itself?

For example, say there is a bunch of Ajax requests in flight and something strange comes back from one of them such that jQuery decides to abort all the others.

Can this ever happen?

Was it helpful?

Solution

Apart from the timeout option, generally jQuery doesn't decide. You decide.

The routine is to always have a reference of what $.ajax() returns you.

Meaning, instead of just calling $.ajax(), do this instead, xhr = $.ajax().

$.ajax() returns you a jqXHR object, which is just a jQuery wrapper of the Ajax functionality. See http://api.jquery.com/jQuery.ajax/

Now that you have xhr, you can call xhr.abort() from anywhere you want.

Really depends on how you design it, but you make the .abort() call. The following might be one possible use case.

One polling function, and another function that checks if user has been idle for too long.

In case the user is idle, abort the polling ajax, then perhaps prompt a message warning the user that the session is over.

Example use case:

var mainXHR; // this is just one reference. 
             // You can of course have an array of references instead

function mainPollingFunction () {
    mainXHR = $.ajax({
        url: 'keepAlive.php',
        // more parameters here
        timeout: 10000, // 10 seconds
        success: function () {
            // server waits 10 seconds before responding
            mainPollingFunction(); // initiate another poll again
        }
    });
}

// Let's say this function checks if the user is idle
// and runs when a setTimeout() is reached
function otherFunction () {
    if ( /* if user is idle */ ) {
        if (mainXHR) mainXHR.abort(); // abort the ajax in case it's still requesting
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top