Wednesday, January 9, 2013

Detecting Ajax Request with PHP Script

Here’s a script that  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.The script is pretty self explanatory,we are  checking to see if the request was sent via an xmlhttprequest.





Example Script :
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!';

No comments:

Post a Comment

Thanks....