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.
$person = array( 'name' => 'Quentin', 'country' => 'Australia' );
{ 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.
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.




