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

Consuming JSON

The final task that we haven't covered yet is parsing JSON on the server side with PHP. There are two parts to this task: generate the JSON request with JavaScript and take that request and return results in JSON format. Just like with the XML format, we need to redesign our results slightly to accommodate multiple queries.

Designing the JSON Request and Response

The JSON request needs to include an array of search terms. The terms will consist of an object that has both a title and an author attribute. Here is an example of the JSON request:

[{"title":"PHP", "author":"curioso"}]

Our response will be the same as the responses from before only we now have to include the query in the response as well as the ability to have multiple responses. To refresh our memory, our old response to the query looked like this:

[{
       "Title":"Ajax with PHP 5",
       "Author":"Andrew Curioso",
       "Year":2007,
       "Publisher":"O'Reilly Media"
}]

When we add our query encapsulation information it looks like this:

[{
       "query":{ title:"PHP", author:"Curioso" },
       "Books":[{
              "Title":"Ajax with PHP 5",
              "Author":"Andrew Curioso",
              "Year":2007,
              "Publisher":"O'Reilly Media"
       }]
}]

The new response includes an array of objects that each contains two members. One of the members is a query object just like the one we send to the server and the other is an array of all the books returned in the result.

Generating the JSON Query with JavaScript

We use almost the same PHP file as with the previous example on consuming XML here. ...

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