I'd like to register a global event handler for all AJAX requests, so that I can intercept and handle responses from the server before the specific event handler gets them.
For example, my code might have something like:
$("#placeholder").load("/fragments/userpics");
And I'd like to register a "before" event handler so that I could, for example, display a login box if a 401 response is returned, or maybe retry if there's a 503 response.
I thought that $.ajaxError()
is where I would do something like this, but apparently it is only triggered after the event handler.
UPDATE: OK, here's what I got so far, with the help of @genesis:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
var success = options.success;
options.success = function(data, textStatus, jqXHR) {
// override success handling
if(typeof(success) === "function") return success(data, textStatus, jqXHR);
};
var error = options.error;
options.error = function(jqXHR, textStatus, errorThrown) {
// override error handling
if(typeof(error) === "function") return error(jqXHR, textStatus, errorThrown);
};
});
After doing some testing, it looks like I would also need to override options.complete
.
However, this still doesn't cover all the bases, since you can also attach events directly to the jqXHR object, and changing options
won't help in this case.
Any tips?