How to tell if it's an AJAX request in PHPHow to tell if it's an AJAX request in PHP

Posted January 12th, 2009 in PHP

Some of the upcoming jQuery posts I will be publishing will be making AJAX requests so I thought it fitting to post how to tell if the incoming request is an AJAX request in PHP for the PHP programmers out there. This is useful if your script handles both AJAX and non-AJAX requests and you need to know which sort it is.

You could simply append a query string to let your script know it's an AJAX request and check for the appropriate $_GET or $_POST variable like so, when you've requested e.g.

/path/to/script.php?ajax

and then testing for it like so:

if(isset($_GET['ajax'])) {
    ... it's an AJAX request so do something ...
}
else {
    ... it's not an AJAX request so do something else ...
}

Fortunately there's an easier way so you don't have to append something to the end of the GET string etc as shown above. This works for jQuery; it may or may not work for other Javascript frameworks.

There's an HTTP variable set called HTTP_X_REQUESTED_WITH, which will be set and set to 'xmlhttprequest' if it's an AJAX query. You can therefore change the above to this:

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    ... it's an AJAX request so do something ...
}
else {
    ... it's not an AJAX request so do something else ...
}

I use strtolower() in my code to lowercase the HTTP_X_REQUESTED_WITH to ensure there are no issues when comparing the string. Another way you could do this is to set a constant in one of your common libraries or initialisation scripts like so:

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

This saves having to copy and paste code and means you can now simply do this when testing if it's an AJAX request and taking appropriate action:

if(IS_AJAX) {
    ... it's an AJAX request so do something ...
}
else {
    ... it's not an AJAX request so do something else ...
}

As mentioned above this works for jQuery with PHP. It may or may not work with other Javascript frameworks. I've only used jQuery to date for dealing with AJAX but will update this in the future if I use other tools such a MooTools, YUI or others.

Related posts:

Comments

blog comments powered by Disqus