Steve Walsh
Steve Walsh

Reputation: 6645

How to handle jQuery ajax post error when navigating away from a page

Is there a way to handle the error from an ajax request within JQuery such that when the user navigates away from the page, the resulting error is ignored?

$(document).ready(function() {
 $.ajax( {
    url:'/server/url/',
    type: 'POST',
    data: {some..data},
    success:function(response) { do stuff with response },
    error: function(xhr, textStatus, errorThrown) {
           // Don't raise this alert if user has navigated away from the page
           alert('error');
    }
});

I'm curious if anybody knows of a clean way to handle this? I know you could create some logic in a $(window).bind("beforeunload", function(){}) method but I'd prefer if there was a way to handle the situation without doing this since Chrome appears to no longer support it. Is there for example a specific error that is returned in this case?

Thanks.

Upvotes: 37

Views: 10724

Answers (3)

Steve Walsh
Steve Walsh

Reputation: 6645

It looks like the answer to this is to examine the jqXHR.status. The XMLHttpRequest spec outlines these steps to set the status:

The status attribute must return the result of running these steps:

  1. If the state is UNSENT or OPENED, return 0 and terminate these steps.

  2. If the error flag is set, return 0 and terminate these steps.

  3. Return the HTTP status code.1

NOTE also: The error flag indicates some type of network error or request abortion. It is initially unset and is used during the DONE state.

From what I understand therefore, this code check should fix the issue:

    if (xhr.status == 0)
        alert('error');

1https://web.archive.org/web/20120204040047/http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute

Upvotes: 19

Kevin Gorski
Kevin Gorski

Reputation: 3769

Checking the status didn't work for me, but

// Ignore incomplete requests, likely due to navigating away from the page
if (jqXHR.readyState < 4) {
    return true;
} 

in the error handler did (4 being DONE).

Upvotes: 14

ori
ori

Reputation: 7847

I've had to handle this issue too a couple of times.

I'd recommend binding to the $(window).unload event, setting some variable somewhere, such as in your namespace (App.unloading = true) and then testing it in ajax error callbacks.

See http://api.jquery.com/unload/

Upvotes: 3

Related Questions