Josh Mc
Josh Mc

Reputation: 10244

How can I tell when AJAX has been intentionally canceled by the browser?

So basically I want to be able to tell the difference between when an ajax call failed naturally (eg 404, server down, etc etc) and when it has been canceled by the browser, eg when a user closes a tab or hits f5.

I listen for failed ajax attempts and display an error dialogue, describing the error when ajax fails. However when someone presses f5 (especially noticeable in firefox), the error callback of not yet complete ajax calls occur, then displays errors and while the page loads the user is stuck looking at the error dialogue until the whole page is torn down by the browser (which is not nice to look at, when in reality it doesn't matter that the ajax call failed because the whole web app is being reloaded).

I have examined the xmlHttp request object, and nothing stands out to me as a way to tell the two situations apart. I have also tried adding a delay, but this hasn't really worked so well either. So I am just wondering if it is possible, and if so how?

Upvotes: 1

Views: 155

Answers (1)

jfriend00
jfriend00

Reputation: 707876

I found a work-around. If you set a window.onbeforeunload handler, that will get called before the ajax error. So, if you set a flag that the document is unloading, you can check that flag before showing your ajax error and skip the error if the document is in the process of unloading.

Works for me with jQuery 1.11 in Firefox, Chrome and IE.

You can see it work here: http://jsfiddle.net/jfriend00/G3wat/

var unloading = false;
$(window).on("beforeunload", function() {
    unloading = true;
});

Then, in your ajax calls:

    error: function(jqXHR, status, err) {
        if (!unloading) {
            alert("Error status " + status);
        }

And, as you found, it appears that jQuery 2.x does this for you.

Upvotes: 2

Related Questions