Nish
Nish

Reputation: 130

A Common Handler for all Ajax Responses

I have more than a dozen ajax calls in the page, all with different purposes. I wanted to know if I can write a function which can catch any ajax call's response on the page. If the response is a text, "Catch me", the function prevents default ajax success function and alerts "Caught"; if not, it follows the default success function.

Basically, can I write a function that catches all ajax calls on the page and checks their response text.

A tedious way would be to edit each ajax call, but I'm trying to avoid that.

Upvotes: 1

Views: 1563

Answers (2)

jwaliszko
jwaliszko

Reputation: 17064

I see that you're trying to create global handler which executes on the response, just before success event. Next, based on some condition, breaks the default behavior (by displaying alert in your case), or passes the flow further (to the custom success event, as each your ajax call can have different logic to run on success).

To do so you should modify the ajax handler provided by jQuery a bit:

var ns = {};
(function(ctx) {
    ctx.ajax = function(options, callback){
        var defaults = {
            success: function (data) {
                if (data != "Catch me") {
                    callback(data);
                } else {
                    alert("Catched");
                }
            }
        };
        $.extend(options, defaults);
        $.ajax(options);
    };   
})(ns);

The ajax call should be invoked just like below:

ns.ajax(options, function (data) {
    alert("success, inside callback");
});

Upvotes: 1

Boyan
Boyan

Reputation: 456

Check out the Global AJAX Event Handlers in jQuery. The page says:

These methods register handlers to be called when certain events, such as initialization or completion, take place for any AJAX request on the page. The global events are fired on each AJAX request if the global property in jQuery.ajaxSetup() is true, which it is by default. Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.

So your code should simply look like this (I used a random selector, it's not necessary to use "body"):

$("body").ajaxComplete(function(e, xhr, settings){ alert(xhr.responseText); });​​​​​​​

Upvotes: 1

Related Questions