How to detect Ajax Request using PHP

If you want to detect whether the request is Ajax request or not, just put the below code at the top of your PHP file. Requests from ajax mostly have X-requested-With header, which is sent by Ajax default in most of the javascript libraries. But few new servers do not set this header and thus it can not predict the request. $_SERVER is mostly supported by all server but it is always a good thing to verify whether your server has such header.

With the request, there’s an HTTP variable set called HTTP_X_REQUESTED_WITH, which will be set to ‘xmlhttprequest’ if it’s an AJAX query.

I used strtolower() in code to ensure that there would be no issues in string comparison.

//detect ajax request
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
   
   die("It's ajax Request!");
   
}

As I mentioned this worked with JQuery and PHP. It might not work with other Javascript libraries or frameworks.