Tuesday, March 31, 2015

How to check if a request is sent using ajax or not - PHP Snippet

How to check if a request is sent using ajax or not - PHP Snippet

Simple php function that let you check whether request is sent via ajax or not.

/*************************************************************************** 
*
* isAjax
* checks whether request is received via ajax call or not
* $_SERVER['HTTP_X_REQUESTED_WITH'] is pivotal here
* If request is via ajax, returns true
* If request is not via ajax, returns false
*
***************************************************************************/
public function isAjax(){
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

// It is an ajax call
return true;
}
else{
// It is not an ajax call
return false;
}
}

Disqus Comments