How to intercept ajax calls in jQuery?

Intercepting ajax requests is useful in some cases. For example, you may want to intercept the url of an ajax request, or you want to intercept the data sent via ajax calls. Sometimes, you may need to intercept the response of ajax requests. By interception of ajax calls, you can get the information sent to the server, and even change it before sending, or modify the response before other handlers get it.

This post is good tutorial about ajax interception technique. Basically, it introduces two ajax interceptors, one is javascript interceptor, the other is jquery interceptor. In that article, the interceptors are used to alter the header of http request(adding Authorization header to the original ajax request). But hijacking ajax request can do much more than modifying http request headers. For example, some people often ask me how to get the post data of ajax post request. According to that article, we give two methods to obtain the post data for ajax calls.
The javacript method

(function(send) {
    XMLHttpRequest.prototype.send = function(body) {
        var info="send data\r\n"+body;
        alert(info);
        send.call(this, body);
    };
})(XMLHttpRequest.prototype.send);

The javacript method re-defines the send function of XMLHttpRequest in its prototype. Every ajax request (even done with jQuery) will call the send function, so our new send function will be called. In the new version of the send function, we print the body which is the data to send. And do not forget to call the original send function, otherwise, the original functionality would be broken.

The jQuery method

$.ajaxSetup({
    beforeSend: function (xhr,settings) {
        alert(settings.data);
        alert(settings.url);
    }
});

The jQuery method uses the $.ajaxSetup which sets up the default settings for the following ajax calls. One of the settings is “beforeSend” which is a callback function invoked when an ajax call occurs and before sending the data. The post data to send is included in the parameter “settings” as settings.data, which you can display or modify as you wish. The above code also intercepts the url of the ajax call, which is read as settings.url.

$.ajaxSetup can also be used to capture the data returned from the server. This time, we set the “dataFilter” parameter.

$.ajaxSetup({
    dataFilter: function (data, type) {
        alert(data);
        return data;
    }
});

Note that after you look at the data or modify it, you must return the data so that it can be consumed by other handlers.

Apart from $.ajaxSetup, there are other jQuery functions such as ajaxSuccess and ajaxError, etc. that can be used to intercept ajax calls. Some are invoked before sending the data to the server, others are invoked after receiving the response from the server.

Comments are closed, but trackbacks and pingbacks are open.