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);
}
});
Problem solved..
I've set a global variable:
Then a
beforeunload
event handle (thanks Dave!), to modify the variable:And finally a cross-reference in the error block of the ajax method:
And yes alerts are ugly and shouldn't be used!
Try...
...where xhr is your XMLHttpRequest variable