PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Detecting Ajax Requests With PHP

In this PhpRiot Snippet I will show you how can detect if a HTTP request was an Ajax request. Ajax requests are performed in JavaScript using the XMLHttpRequest component.

When such a request is made, a HTTP header called X-Requested-With is sent. The corresponding value for this header is XMLHttpRequest. You can access these headers from the PHP superglobal $_SERVER.

PHP renames HTTP request headers so dashes become underscores and all letters are made upper-case. Therefore we can check $_SERVER['X_REQUESTED_WITH'].

Therefore you can use the following code to check if a request is from an Ajax request.

Listing 1 Checking if a request is an Ajax request (listing-1.php)
<?php
    $isXmlHttpRequest = array_key_exists('X_REQUESTED_WITH', $_SERVER) &&
        $_SERVER['X_REQUESTED_WITH'] == 'XMLHttpRequest';
 
    if ($isXmlHttpRequest) {
        // is an Ajax request
    }
    else {
        // is not an Ajax request
    }
?>
If you're using Zend_Controller_Front, you can call the the isXmlHttpRequest() method on the request object.

Being able to check if a request is useful to determine what kind of content to send back. For example, if the request is an Ajax request you may want to send back some JSON data, whereas if it's not you may just want to return normal HTML.

In the following listing I demonstrate this. If the request is an Ajax request we sent some JSON data back, otherwise we fall through and output normal HTML.

Listing 2 Outputting JSON data for Ajax requests only (listing-2.php)
<?php
    $isXmlHttpRequest = array_key_exists('X_REQUESTED_WITH', $_SERVER) &&
        $_SERVER['X_REQUESTED_WITH'] == 'XMLHttpRequest';
 
    if ($isXmlHttpRequest) {
        $data = array(
            'foo' => 'bar'
        );
 
        header('Content-type: application/json');
        echo json_encode($data);
        exit;
    }
?>
<html>
    <head><title>Normal page content</title></head>
    <body>
        <!-- normal page content -->
    </body>
</html>

Other Options

Detecting Ajax Requests With PHP