We use jQuery's global ajaxError() handler to alert the user of any AJAX failures:
$(document).ajaxError(function() {
$("There was a network or server error. Please try again later.").dialog({
title: "Error",
modal: true,
resizable: false,
buttons: { 'Ok': function() { (this).dialog("close"); } }
});
});
Unfortunately, this global error handler also fires if the user leaves the page before it finishes loading. Here are the steps to reproduce the error:
- User visits Page A, which includes elements that load via AJAX.
- AJAX elements on Page A begin loading.
- User clicks link to visit Page B before AJAX elements on Page A have finished loading.
- The error dialog box appears briefly before the browser redirects to Page B.
Any idea how we can get ajaxError() not to trigger when the error is directly caused by the user visiting a new page?
UPDATE: Here's my code now, after incorporating the suggestions in the comments:
// I added a 3 second delay to our error dialog, enough time
// for the user to leave for a new page:
$(document).ajaxError(function() {
setTimeout(my_error_handler, 3000);
});
// Warn user before leaving page if AJAX is still loading.
// Not sure I'll keep this:
$(document).ajaxStart(function() {
ajaxing = true;
});
$(document).ajaxStop(function() {
ajaxing = false;
});
window.onbeforeunload = function() {
if (typeof(ajaxing) != 'undefined' && ajaxing) {
return "Page elements are still loading!";
}
};