This simple script checks for the X-Requested-With
header that most common JavaScript frameworks and libraries will set to XMLHttpRequest
if sending a request via AJAX.
The function can be useful in determining what sort of response to send back to the client. For example a JSON response or a full HTML response.
/**
* Is the Request an AJAX Request?
*
* This works if your JavaScript library sets the X-Requested-With HTTP header. Most common JavaScript frameworks do:
*
* @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
*
* @return bool Returns true if the request is an AJAX request, false otherwise
*/
function isAjax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
This code snippet was published on It was last edited on