views:

150

answers:

2

I want to be able to call a URL be either a standard HTTP GET, or an AJAX call.

The server needs to handle the request slightly differently based on whether the request was an AJAX request or not.

Using jQuery, I want to automatically add a parameter to all AJAX requests I make, so that the server can identify them, and without me having to add the parameter everywhere I make a call.

I've tried doing this with a jQuery.ajaxSend event handler, but at that point, the XMLHttpRequest is already constructed, and making changes to the URL or data members of the ajaxOptions object has no effect, and I don't know how to reliably manipulate the XMLHttpRequest object (I can examine it in Firebug, but I don't know what I can expect work in a cross-browser manner).

How should I achieve this? Is there a better way to identify AJAX requests?

+2  A: 

I think it would be better and simpler to test for the x-requested-with header with value set to XMLHttpRequest on the server side, to differentiate ajax requests from normal ones. Note: it is very easy to spoof that header. Here's a simple PHP example:

function isAjax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
         ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}

if(isAjax()) { 
    // do something
} else {
    // do something else, or nothing
}
karim79
Are you always guaranteed to get this header? Across all browsers? That it's easy to spoof the header is unimportant, there's no extra data exposed, it's just returned in a different format.
SpoonMeiser
@SpoonMeiser - I'm fairly certain you are, I am using code such as the above in production, and it works across all browsers I've tested on (the same ones supported by jQuery).
karim79
@SpoonMeiser - it is sent by all recent browsers that support ajax requests AFAIK.
karim79
+1  A: 

Just make your own function that calls $.ajax but adds it in:

function myAjax(opts) {
    opts.data = opts.data || {};  // make sure it exists
    opts.data.myParam = "42";
    $.ajax(opts);
}

Then call that elsewhere. As karim79 says, you can also check for the X-Requested-With: XMLHttpRequest header. But yeah, both ways are pretty easy to spoof, so take what the client sends you with a grain of salt.

Anthony Mills