jQuery Ajax error resolution
-
06-07-2019 - |
Question
I'm working on a stripes app that uses a bit of jQuery to make the UI more dynamic/usable.
I set up an Error Resolution, so if an error is thrown, the user is redirected to an error.jsp page.
However, if an error is thrown during a jQuery Ajax call, instead of redirecting to the error.jsp page, I get html printed to the page where the result of the call should have been instead.
How do I tell jQuery to redirect if an exception was thrown instead of printing to the page?
An example of the offending Ajax:
$.post("SendStatusEmail.action",
{status: newstatus, id : id },
function(data) {
column.text(data);
column.addClass("redfont");
column.parent().fadeOut(3000, function(){column.parent().remove()});
Solution
$(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) {
// redirect here.
}
I should add that I don't redirect when there is an exception in an Ajax call. Instead, I have the server return an error description in JSON format and display that in the page.
OTHER TIPS
What about using $.ajax() instead of $.post()? The more general $.ajax() offers an error callback that you can call in case of an error.