Differentiating Between an AJAX Call / Browser Request
-
03-07-2019 - |
Question
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?
Solution
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');
OTHER TIPS
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.