5

I am using the following code to asynchronously pull data from the server into the client. The alert in the error block reports errors that occur on the server. However if the user navigates away from the page page mid-call, this block also gets fired and throws an empty alert container. Is there any way to handle the the user leaving the page more gracefully (i.e. not throw an empty alert before they leave)? Maybe by differentiating in the error block that the user has navigated away, rather than an error occurring on the server?

$.ajax({
    type: "GET",
    url: "/handlers/myHandler.ashx",
    async: true,
    dataType: "json",
    data: "var1=test_val&var2=test_val"
    success: function (invoices) {
       //Success block
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
    }
});
QFDev
  • 8,668
  • 14
  • 58
  • 85
  • 1) You should use a HTML element to report failure, rather than alert (which is a pretty old-and-ugly way to give information). 2) You can try adding a hook for `unload` or `beforeunload` to the page which sets a variable to prevent the error, but I don't know if the order of events will be correct. 3) You can simply avoid showing a message if it will be empty. – Dave Mar 10 '13 at 19:42
  • Thanks, and I agree, the 'alert' was used in the early days of our application for convenience. I'll look into those events. – QFDev Mar 10 '13 at 20:26
  • Possible duplicate of [How to handle jQuery ajax post error when navigating away from a page](http://stackoverflow.com/questions/9229005/how-to-handle-jquery-ajax-post-error-when-navigating-away-from-a-page) – romor Feb 16 '16 at 20:23

2 Answers2

4

Try...

if (xhr.status != 0)
  alert(thrownError);

...where xhr is your XMLHttpRequest variable

Michael
  • 514
  • 4
  • 11
1

Problem solved..

I've set a global variable:

var unloadingState = false;

Then a beforeunload event handle (thanks Dave!), to modify the variable:

$(window).bind("beforeunload", function () {
    unloadingState = true;
});

And finally a cross-reference in the error block of the ajax method:

error: function (XMLHttpRequest, textStatus, errorThrown) {
  if (!unloadingState) {
    alert(errorThrown);
  }
}

And yes alerts are ugly and shouldn't be used!

QFDev
  • 8,668
  • 14
  • 58
  • 85