Branching off of questions like this one, I'm looking to wrap jQuery's $.ajax() method such that I can provide error handling in one location, which would then be used automatically by all of an application's remote calls.
The simple approach would be to simply create a new name, similar to how $.get() and $.post() implement facades to $.ajax(). However, I'm hoping to reuse the name $.ajax(), such that we can keep the rest of our code using the standard jQuery syntax, hiding from it the fact that we've added our own error handling. Is this practical and/or good to achieve, or possibly a horrible idea?
EDIT: The responses so far indicate .ajaxError() is the way to go. I know this will catch 400 and 500 level errors, but is there a way (with this event handler or otherwise) to catch 302 redirects as well? I'm trying to handle responses that are redirecting to a login page, but we want to intercept that redirect when it's an XHR request, allowing the user to cancel the action instead of forcing them forwards automatically.
You might want to look at
$.ajaxError
.jQuery provides a whole bunch of other ways to attach global handlers.
To answer your edit, you can catch successful ajax requests with
$.ajaxSuccess
, and you can catch all (successful and failed) with$.ajaxComplete
. You can obtain the response code from thexhr
parameter, likeI think it's a bad idea. I think wrapping
$.ajax
is fine, but you're talking about re-defining it. Anyone who doesn't realize this will get unexpected results.As others have mentioned, binding a handler to
$.ajaxError
is the way to go.Actually, jQuery provides the hook,
.ajaxError()
just for this purpose. Any and all handlers you've bound with$ajaxError()
will be called when an ajax request from page completes with an error. Specifying a selector allows you to referencethis
inside of your.ajaxError()
handler.To use it to handle all ajax request errors on the page and use
this
to point todocument
, you could do something like this:jQuery has a handy method called $.ajaxSetup() which allows you to set options that apply to all jQuery based AJAX requests that come after it. By placing this method in your main document ready function, all of the settings will be applied to the rest of your functions automatically and in one location
Reference: https://cypressnorth.com/programming/global-ajax-error-handling-with-jquery/