Skip to Main Content
Ajax with PHP 5
book

Ajax with PHP 5

by Andrew Curioso
May 2007
Intermediate to advanced content levelIntermediate to advanced
56 pages
1h 34m
English
O'Reilly Media, Inc.
Content preview from Ajax with PHP 5

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Pro PHP and jQuery

Pro PHP and jQuery

Jason Lengstorf
Expert PHP and MySQL®

Expert PHP and MySQL®

Andrew Curioso, Ronald Bradford, Patrick Galbraith

Publisher Resources

ISBN: 9780596514037Purchase LinkErrata Page