Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
273

■ ■ ■


CHAPTER 18


Ajax and JSON


Ajax, short for Asynchronous JavaScript and XML, is a combination of technologies, typically
JavaScript and XML. It is used to create “rich applications” that can retrieve and submit data
through their interface without reloading the web page.
The Ajax term is somewhat controversial. The concept of Ajax has been around for a very
long time, but the term is a recent invention and scorned by some JavaScript developers. They
continue to call Ajax XHR, short for XmlHttpRequest, which is the name of the core JavaScript
object that makes Ajax applications run.
In addition to the XHR object, Ajax applications will also typically use the browser Docu-
ment Object Model (DOM) to access HTML and update the content on the page. It is this binding
between the DOM and HTML that makes the Ajax technique so powerful. This technique can
be used to create partially updating web sites that are more responsive than a complete page
reload.
The XHR component is a way to send data. Usually, this data is encoded in XML; however,
there is no hard requirement that XML be used to encode data for transport. Because of this
flexibility and the relative weight of processing XML, most applications would benefit from a
simpler data format, and thus JSON was packaged.
JSON, short for JavaScript Object Notation, is a data-encoding format that is based on
JavaScript itself. In fact, JSON datagrams can be evaluated as if they were code using the eval()
function, and as such, require almost no processing on the client side to decode. This means
that on the client side, you do not need to engage in parsing XML documents, and this may
save you significant programming time and some CPU cycles on the client machine.
In this chapter, you will learn about Ajax, JSON, and the PHP JSON extension. You will also
learn how to interact with JSON from the Zend Framework classes. Finally, you will create a
couple of sample projects that demonstrate GET and POST processing using these techniques.

JSON and PHP


The detail of the JSON encoding is not particularly important to PHP developers, as most of
your interaction with JSON will be calling functions to encode and decode data in JSON format.
PHP’s responsibility in the Ajax/JSON relationship is to understand JSON datagrams posted to
it and return JSON-encoded data back to the browser. What is important to know is that JSON
is a replacement for XML in Ajax applications.

McArthur_819-9.book Page 273 Friday, February 29, 2008 8:03 AM

Free download pdf