Reputation: 29342
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?
Upvotes: 21
Views: 25039
Reputation: 6882
Hugo Forte has the correct answer, the only way to intercept an Ajax response before any event handlers are called is to use dataFilter.
I had to use this today to handle redirecting ajax responses on the client side without refactoring the code too much.
$.ajaxSetup({
dataFilter: function (data, type) {
if (data !== "" && data === "NOAUTH") {
window.location = '/';
}
return data;
}
});
Upvotes: 2
Reputation: 5978
If you want to handle the data coming back from the server before the event handler, use datafilter:
jQuery.ajaxSetup({
dataFilter: function (data, type) {
//modify the data
return data;
}
});
Upvotes: 26
Reputation: 50976
Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().
http://api.jquery.com/jQuery.ajaxPrefilter/
I bet it works for .load(), too
Upvotes: 8