13

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?

bignose
  • 30,281
  • 14
  • 77
  • 110
Wilco
  • 32,754
  • 49
  • 128
  • 160

2 Answers2

34

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
  • 295,876
  • 54
  • 310
  • 348
  • http://trac.dojotoolkit.org/ticket/5801 according to above, jQuery, Prototype, YUI, Mootools send the header – Gene T Oct 19 '08 at 11:05
  • 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 Oct 19 '08 at 11:28
  • ...and Mootools can be checked here http://github.com/mootools/mootools-core/tree/master/Source/Request/Request.js – Paul Dixon Oct 19 '08 at 11:29
  • ...and YUI can be checked here http://developer.yahoo.com/yui/docs/connection.js.html – Paul Dixon Oct 19 '08 at 11:38
0

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
  • 32,754
  • 49
  • 128
  • 160
  • 1
    If you're going to do that then why not simply append an extra query parameter to distinguish AJAX requests instead? – John Topley Oct 19 '08 at 08:55
  • 5
    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 Oct 19 '08 at 09:47
  • The problem with extra query parameters is that users can see source - view source and try to make a call with those parameters.. – Vijeet Deliwala Feb 18 '14 at 12:52