Paul
Paul

Reputation: 3954

Stopping an $.ajax call on page unload

I have a procedure running on a timeout to load data in the background:

(function getSubPage() {
    setTimeout(function() {
        if (cnt++ < pagelist.length) {
            loadSubPage(pagelist[cnt]);
            getSubPage();
        }
    }, 500);
})();

In loadSubPage() I'm making $.ajax() calls:

function loadSubPage(page) {
    if (typeof(initSubPages[page]) === "undefined") {
        $.ajax({
            type: "POST",
            url: '/Main/GetPageData',
            data: { page: page },
            success: function (returndata) {
                // ...
            },
            error: function() {
                alert("Error retrieving page data.");
            }
        });
        initSubPages[page] = true;
    }
}

The problem I'm having is that the error handler is being hit when the user navigates away if any ajax requests are open. I'm trying to get around this by .stop()ing the requests on window.onbeforeunload, but I'm not sure what object to call .stop() on?

Upvotes: 2

Views: 2545

Answers (4)

Paul
Paul

Reputation: 3954

Here is the solution I used based on the feedback:

window.onbeforeunload = function() {            
    for (page in ajaxing) {
        if (ajaxing[page] != null)
            ajaxing[page].abort();
    }
};

var ajaxing = {};

function loadSubPage(page) {
    if (typeof(initSubPages[page]) === "undefined") {
        var ajaxRequest = $.ajax({
            type: "POST",
            url: '/Main/GetPageData',
            data: { page: page },
            success: function (returndata) {
                 // ...
            },
            error: function() {
                alert("Error retrieving page data.");
            },
            complete: function() {
                ajaxing[lot] = null;
            }
        });
        ajaxing[page] = ajaxRequest;
        initSubPages[page] = true;
    }
}

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

The $.ajax returns XMLHTTPRequestObject which has .abort function. This function will halt the request before it completes.

var xhr = $.ajax({ /*...*/

..
..
/* Later somewhere you want to stop*/
xhr.abort();

Read more: How to cancel/abort jQuery AJAX request?

Upvotes: 0

iMoses
iMoses

Reputation: 4348

Abort Ajax requests using jQuery

This should come in handy.. You have a jQuery method for doing just that.

Upvotes: 0

epascarello
epascarello

Reputation: 207501

jQuery exposes the XMLHttpRequest object's abort method so you can call it and cancel the request. You would need to store the open request into a variable and call abort().

activeRequest = $.ajax({...

and to stop it

activeRequest.abort()

Upvotes: 4

Related Questions