O'Reilly logo

Ajax with PHP 5 by Andrew G. Curioso

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required