Detecting an Ajax Request with PHP

Here’s a quick piece of code that i find useful to check if a request that comes to a PHP page was made via an Ajax call or a simple form post. This method uses the $_SERVER[‘HTTP_X_REQUESTED_WITH’] request to determine if data was sent to a specific page using an xmlhttprequest. It’s worth bearing in mind that there is no guarantee that every web server will provide this setting, servers may omit specific $_SERVER parameters, That said, a large number of these variables are accounted for, you can find more information about $_SERVER variables here.

cdl_capture_2012-06-05-30_ 000

The PHP

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')

{

// If its an ajax request execute the code below

echo 'This is an ajax request!';

exit;

}

//if it's not an ajax request echo the below.

echo 'This is clearly not an ajax request!';

The code is pretty self explanatory we are literally checking to see if the request was sent via an xmlhttprequest. In the Demo below i’ve setup a page that contains a jQuery Ajax request to our code above and a simple form with a button that just submits to the same page.

Demo

http://papermashup.com/demos/ajax-check/

Leave a comment