Detect an Ajax request in PHP

Posted by Stanislav Furman  on August 25, 2017

If you would like to use same PHP code to handle both AJAX and non-AJAX requests, here is a quick and simple trick that you can use to check if the incoming request is AJAX. For our trick we will use a HTTP header called HTTP_X_REQUESTED_WITH. It is supported by all modern browsers that support AJAX. Therefore, it should work in 99% of cases.


<?php 
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
	// handle request as AJAX
	echo json_encode(["message"] => "This is AJAX"); 
	exit;
} 
echo "This is not AJAX";
?>

It's just as simple as that. Using one same PHP code for handling AJAX and non-AJAX requests makes it easier to maintain.


Leave your comment

Fields with * are required.

* When you submit a comment, you agree with Terms and Conditions of Use.