Serving JSON

Up until this point we have used two methods of transferring data from the server to the client. Plain text was used in "Hello World" and XML was used in the previous section. Here, we cover JavaScript Object Notation (JSON), which is another popular method for transferring the data. Both have their benefits and there have been extensive debates on the Internet over which is better to use in Ajax applications.

JSON (see http://www.json.org) is described as a "lightweight data-interchange format." This means that you can transfer data without much overhead. In fact, even though the XMLHTTPRequest object only contains built in support for plain text and XML, getting started with a JSON implementation is as simple as one line of code.

The ease of implementation and its lightweight nature make JSON an attractive choice for many PHP developers.

In this section we rewrite the example from the previous "Serving XML" section to use JSON instead. There is very little new code to introduce here, but we do go over the JSON concepts in depth.

Designing the JSON File

JSON is very good at transferring two types of data. These two main types are arrays and objects. In XML, we had a root element that can contain numerous sub elements. These elements were collectively called nodes. In JSON, the two structures closely model the programming language that they are implemented in. Instead of nodes, we have data structures.

Arrays in JSON

The first type of data structure we will study is an array. ...

Get Ajax with PHP 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.