views:

50

answers:

2

Hi,

I would like to extend jQuery such that every post/get request made on the client side will have an additional parameter sent (always the same key : value). I need this to detect on the client side if the request was made through jQuery, since I have several js libs at work. The additional param is simply jquery : true. A typical request will normally look like this:

jQuery.post('/users/save', { name : 'john', age : 24 }, ....)

Is there a way to append this addition parameter by extending jQuery or some other way such that it'll look like so when it reaches the server:

{ name : 'john', age : 24, jquery : true }

Basically I want to intercept the request and edit it's parameters before they reach the server side. thanks.

+1  A: 

Look at beforeSend(XMLHttpRequest)

A pre-callback to modify the XMLHttpRequest object before it is sent. Use this to set custom headers etc. The XMLHttpRequest is passed as the only argument. This is an Ajax Event. You may return false in function to cancel the request

You should be able to use it with ajaxSetup

nc3b
+1  A: 

Try putting the following somewhere in your code before any AJAX request would be executed:

$.ajaxSetup({
    beforeSend: function(xhr) {
        var newUrl = this.url;
        if (newUrl.indexOf("?") != -1) {
            newUrl = newUrl + '&jquery=true';
        } else {
            newUrl = newUrl + '?jquery=true';                
        }
        xhr.open(this.type, newUrl, this.async);
    }
});

This will trigger a function before the sending of any AJAX request. The function determines what the new URL should be (based on whether or not any query string has already been attached), then reopens the XMLHttpRequest with the 'jquery=true' attached at the end.

Here's a working demo of this: http://jsfiddle.net/uz9zg/

Ender