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

Eight Weeks of Prototype: Week 5, Ajax with Prototype

Handling Ajax Requests on the Server Side Using PHP

Now that you have some understanding of how JSON data works, I'll give you a concrete example of performing an Ajax request which returns some JSON data. Additionally, I'll now show you how to handle Ajax responses in PHP. The principles here apply to other languages also, but the server-side language used is PHP.

When writing scripts in PHP to handle Ajax requests, you typically write your scripts as you would for normal requests. The key difference is that you will typically want to set the content type of the response data. By default, PHP uses a content type of text/html, so if you're just sending HTML data back (as we did in listings 3 and 9), you don't need to set the content type.

Let's now look at how to send JSON data in PHP. According to RFC 4627 (which you can find at http://www.ietf.org/rfc/rfc4627.txt), you should use the content type of application/json when sending JSON data.

As I mentioned in the previous section, PHP provides a function called json_encode() which you can use to convert a PHP variable (such as an array) into JSON format. You can use header() to send the content type, then echo the output from json_encode().

Listing 13 Sending a PHP array as JSON data (listing-13.php)
<?php
    $person = array(
        'name'    => 'Quentin',
        'country' => 'Australia'
    );
 
    header('Content-type: application/json');
 
    echo json_encode($person);
?>

We can now build on the code from Listing 12 to actually request this data and display it accordingly. Listing 14 shows the complete example of reading JSON from the server. When you click the button that is displayed, the Ajax request will be initiated. The response will then be displayed. Note however that there is no error handling in this example and it assumes that specific data will be returned.

Listing 14 Reading JSON data from the server (listing-14.html)
<html>
    <head>
        <title>Reading JSON data from the server</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div>
            <input type="button" value="Click Me!" id="myButton" />
        </div>
 
        <script type="text/javascript">
            function onSuccess(transport)
            {
                var json = transport.responseJSON;
 
                alert(json.name + ' is from ' + json.country);
            }
 
            function onButtonClick(e)
            {
                var options = {
                    method    : 'get',
                    onSuccess : onSuccess
                };
 
                new Ajax.Request('listing-15.php', options);
            }
 
            $('myButton').observe('click', onButtonClick);
        </script>
    </body>
</html>

When handling an Ajax request on the server-side, you may want to ensure that the request did in fact come via Ajax. Whenever a request is performed using Prototype's Ajax.Request, the header X-Requested-With header is sent, with a value of XMLHttpRequest.

While this value can be manually set by a clever user, ultimately it doesn't matter too much and simply allows you perform different functionality if a random user happened to stumble across your Ajax request handler.

Listing 15 shows an example of checking for this header. This is a modification of Listing 13, in which we send a different content type based on how the request is performed. Try viewing this script in your browser. Realistically you may prefer to redirect to another page rather than what is done here.

Listing 15 Checking the request method for the current script (listing-15.php)
<?php
    $person = array(
        'name'    => 'Quentin',
        'country' => 'Australia'
    );
 
    $isXmlHttpRequest = isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
                        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
 
    if ($isXmlHttpRequest)
        header('Content-type: application/json');
    else
        header('Content-type: text/plain');
 
    echo json_encode($person);
?>

In PHP, you read the header from $_SERVER. PHP modifies the request header names by prepending HTTP_, capitalizing the name and replacing hyphens with underscores. In other words, X-Requested-With becomes HTTP_X_REQUESTED_WITH. Additionally, I like to use strtolower() on this value so there is no confusion between, say, XMLHttpRequest and XmlHttpRequest.

In This Article