PhpRiot
Download This Article
Download this article or the entire “Eight Weeks of Prototype” series with all listings and files.




More information
Related Books
Prototype and Scriptaculous in Action [Ajax]

Prototype and Scriptaculous in Action [Ajax]

Prototype and Scriptaculous are libraries that extend standard Ajax. They make it easier to...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

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


Tagged in , , , ,