2

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?

Paul
  • 3,725
  • 12
  • 50
  • 86

4 Answers4

4

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()
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

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?

Community
  • 1
  • 1
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
0

Abort Ajax requests using jQuery

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

Community
  • 1
  • 1
iMoses
  • 4,338
  • 1
  • 24
  • 39
0

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;
    }
}
Paul
  • 3,725
  • 12
  • 50
  • 86