views:

951

answers:

2

Is there anything in the header of an HTTP request that would allow me to differentiate between an AJAX call and a direct browser request from a given client? Are the user agent strings usually the same regardless?

A: 

After some research, it looks like the best approach would be to simply specify a custom user agent string when making AJAX calls and then checking for this custom user agent string on the server.

Wilco
If you're going to do that then why not simply append an extra query parameter to distinguish AJAX requests instead?
John Topley
Indeed. The extra query parameter method is more reliable than a custom header or UA string, as you never know what proxies are going to do. Security proxies hiding the UA string is not uncommon.
bobince
+23  A: 

If you use Prototype, jQuery, Mootools or YUI you should find a X-Requested-With:XMLHttpRequest header which will do the trick for you. It should be possible to insert whatever header you like with other libraries.

At the lowest level, given a XMLHttpRequest or XMLHTTP object, you can set this header with the setRequestHeader method as follows:

xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
Paul Dixon
http://trac.dojotoolkit.org/ticket/5801according to above, jQuery, Prototype, YUI, Mootools send the header
Gene T
Good call, I'll edit. Though I don't use jQuery, I just verified it did it by checking the source here http://jqueryjs.googlecode.com/svn/trunk/jquery/src/ajax.js
Paul Dixon
...and Mootools can be checked here http://github.com/mootools/mootools-core/tree/master/Source/Request/Request.js
Paul Dixon
...and YUI can be checked here http://developer.yahoo.com/yui/docs/connection.js.html
Paul Dixon