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
2008-10-19 08:48:20
If you're going to do that then why not simply append an extra query parameter to distinguish AJAX requests instead?
John Topley
2008-10-19 08:55:13
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
2008-10-19 09:47:15
+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
2008-10-19 08:49:40
http://trac.dojotoolkit.org/ticket/5801according to above, jQuery, Prototype, YUI, Mootools send the header
Gene T
2008-10-19 11:05:16
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
2008-10-19 11:28:46
...and Mootools can be checked here http://github.com/mootools/mootools-core/tree/master/Source/Request/Request.js
Paul Dixon
2008-10-19 11:29:23
...and YUI can be checked here http://developer.yahoo.com/yui/docs/connection.js.html
Paul Dixon
2008-10-19 11:38:38