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

Using JSON Data

I've mentioned JSON a few times in this article so far, but what exactly is it? Short for JavaScript Object Notation, it is a way to send complex data structures between the client and server.

Essentially, it is just JavaScript code. However, it is really only the code that would be used to create a new array or object in JavaScript. Therefore, when you read the JSON data you can bind it to a JavaScript variable and access the response just as you would from any other array or object in JavaScript.

For example, if you wanted to create an array of data in PHP, then make that data easily accessible in JavaScript (let's say you wanted to send this PHP array back in an Ajax response), then you would use JSON.

Listing 10 shows an example of some data you are representing in PHP that you want available in JavaScript. Listing 11 shows the JSON representation of this data.

Listing 10 Some sample data in PHP that we want to use in JavaScript (listing-10.php)
<?php
    $person = array(
        'name'    => 'Quentin',
        'country' => 'Australia'
    );
?>
Listing 11 The $person array represented in JSON (listing-11.js)
{
    name    : 'Quentin',
    country : 'Australia'
}

This data is in the same format as JavaScript uses, meaning you can easily use it in your JavaScript code. Listing 12 shows how you might access this data using the responseJSON variable in your onSuccess handler for Ajax.Request. This assumes that the $person array was the only data sent in the response. In this example I assigned the JSON data to a variable called json, purely so the code is easier to read when the data is accessed.

Listing 12 Reading the JSON response (listing-12.js)
function onSuccess(transport)
{
    var json = transport.responseJSON;
 
    alert(json.name + ' is from ' + json.country);
}

PHP provides the json_encode() function to convert a PHP variable into its equivalent JSON format. This is only available from PHP 5.2.0. I'll show you how to use this function in the next section.

In This Article