Working with AJAX Data

In This Chapter

Understanding the advantages of server-side programming Getting to know PHP
Writing a form for standard PHP processing Building virtual forms with AJAX Submitting interactive AJAX requests Working with XML data Responding to JSON data
JAX and jQuery are incredibly useful, but perhaps the most important use of AJAX is to serve as a conduit between the Web page and programs written on the server. In this chapter, you get an overview of how programming works on the Web server. First you look at traditional server-side programs, and then I explain how AJAX changes the equation. You find out the main forms of data sent from the server and how to interpret this data with jQuery and JavaScript.

Getting an Overview of Server-Side Programming

The JavaScript programming you do throughout this topic primarily works on the Web browser — the client. However, all Web programming also has a relationship with the machine that hosts Web pages — the server. In the examples so far, the Web page is retrieved from the server, and then the JavaScript programs inside the page are executed by the client machine. This is a very powerful approach, but it does have limitations. Most importantly, client-side code cannot store data or access external programs for security reasons.
Fortunately, there’s a solution. You can also write programs that reside on the Web server. They work a little differently than client-side programs. A server-side program runs on the Web server, and when it’s done, it produces an ordinary Web page. The Web page is then sent to the client, where it’s interpreted by the browser.
Server-side programs are processed before the data is transmitted to the browser, and client-side programs are processed after the transmission.
You can do things on the server that aren’t allowed on the client, including storing data and accessing external programs. These are the two things that client-side programs can’t do, so server-side programming is a perfect match for the client-side skills described in this topic.

Introducing PHP

Several languages are used for server-side programming. The most popular of these are PHP, Java, and ASP.NET. For the examples in this topic, I concentrate on PHP:
‘ It’s very popular. PHP is used on thousands of Web sites and has a massive following among programmers.
‘ It’s quite powerful. Although PHP isn’t quite as powerful as some languages, it’s robust enough to support some very large sites (like Facebook and Flickr).
‘ It’s entirely free. PHP is an open-source language, which means it doesn’t cost anything and can be freely modified. You also don’t need to purchase any special editor to write PHP — the text editors you already use are perfectly fine.
‘ It’s readily available. Pretty much every commercial server and even some free servers support PHP. You generally have to pay more for a custom server to handle Java or ASP.NET.
It’s pretty easy. Although PHP isn’t exactly like JavaScript, it’s quite similar. You’ll be able to transfer much of your programming knowledge to PHP with only a few details to worry about.
Although you can practice JavaScript on a standalone computer, PHP only works through a Web server. If you want to experiment with PHP, you must have access to a Web server with PHP installed. There are two main ways to do this:
Get an online account. If you have a hosting account for your Web pages, you probably already have support for PHP. You might need to check your control panel to see whether there are any restrictions or details you need to know. Many free accounts include PHP access, so you can try PHP without any cost to see if you like it. (The hosting service I use offers quite a good free service with PHP access. Check
Install your own Web server. If you want to practice on your own computer, you can install your own Web server. The best way to do this is with a complete installation like XAMPP ( en/xampp.html). The XAMPP package is a complete installation of all the tools you need including a Web server (Apache) programming languages (PHP and Perl) a database package (MySQL) and some other goodies, all configured to work together. XAMPP is available for all major operating systems, but if you’re running Linux, you might already have everything you need.
Note that you can write PHP programs on any computer with the same text editor you use for other Web programming, but you can test PHP programs only when your program runs directly through a Web server. This is necessary because the Web server actually runs PHP before the user sees the page. If there is no Web server (or it is not configured properly), the PHP code will not execute.
Aptana (see Chapter 1) has a great PHP mode, but you’ll have to download a free add-on to get this capability. Go to the My Aptana window (from the Window menu) and click the Plugins tab. You should see a link to download and install the PHP plugin. With the plugin installed, you’ll have the same features (syntax highlighting, syntax completion, integrated help, and so on) with PHP that you already have for the other Web languages.

Writing a form for PHP processing

The best way to see how server-side programming (and PHP) works is to look at a simple example. Figure 14-1 illustrates a basic XHTML Web page with a form.
The page doesn’t look too scary, but it does have an interesting twist. There is no JavaScript code in this form. When the user clicks the button, information is sent to the server, which finds a new program. This program (greetUser.php) examines the contents of the form and composes a new page in reply, which is shown in Figure 14-2.
This Web page has a form.
Figure 14-1:
This Web page has a form.
In server-side programming, the result is an entirely different
Figure 14-2:
In server-side programming, the result is an entirely different
This example points out a key difference between client-side and server-side processing: On the client (in JavaScript), your code resides on the Web page and modifies the same page. In server-side programming (like PHP), the request form and the response are entirely different pages. Typical PHP code involves building an entirely new page from scratch for the result.

Begin by looking at the XHTML source code:

It’s nothing too shocking, but if you’re used to writing forms for JavaScript, you’ll see there are a few differences when you write a form for server-side processing:
1. No JavaScript is necessary.
It’s possible to use client and server programming techniques together (in fact that is the point of AJAX), but it isn’t necessary. For this first example, all code will be processed on the server.
2. Designate a target program in the form’s action attribute.
When you create a form for JavaScript use, the action attribute is empty, indicating that all processing will happen on the current page. For server-side processing, indicate the name of the program that will read the form data (in this case, greetUser.php) in the action attribute.
3. Determine the transfer method.
There are two main ways to transmit form data to the receiving program. The get mechanism embeds data in the URL. This technique is useful for debugging (as the data is visible), but gets awkward for large forms. The post technique is preferred for larger forms, as it sends the data through a less visible mechanism.
4. Add a name attribute to form fields.
In client-side programming, you typically use the id attribute to identify fields. Server-side programs prefer the name identifier. You can (and often will) use both. For this example, I’ve named the single text field userName.
5. Include a submit button.
For client-side processing, you normally use a standard button. Server-side programming typically requires a submit button instead. When the user clicks the submit button, all the data in the form is automatically packaged and sent to the program indicated in the form’s action attribute.
If you get an error message when you submit this program, make sure you’re running it correctly. If the URL in your browser begins with file://, you’re bypassing the server. This method is fine in client-side programming, but it doesn’t work when you’re messing with the server. You need to have an address that begins with http:// in order for server-side programs to work correctly.

Responding to the request

When the user clicks the submit button of nameForm.html, the form information is bundled and passed to the greetUser.php program. If you look over the code for this program, you might find it surprisingly familiar:
For the most part, a PHP program looks a lot like an XHTML page, because mostly that’s what it is. The general structure is just like XHTML. There are only a few key differences.
1. The filename must end with .php.
This indicates to the server that the page isn’t ordinary HTML but will need to be passed through the PHP interpreter before being sent to the user.
2. The <?php marker indicates a switch to PHP syntax.
Most of this page is standard XHTML (and can include CSS and JavaScript, too). In the middle of the page, I indicate that a section of code should be processed by PHP. I signify this with the <?php symbol. (Occasionally you’ll see other variations, but this almost always works.)
3. Make a variable called $userName.
PHP supports variables just like JavaScript, but PHP variable names always begin with the dollar sign ($). This turns out to be quite useful (as you’ll see in a moment).
4. Grab the value of the userName field from the previous form.
PHP has a structure called $_REQUEST, which is a package of all the data sent from the form. You can find the data in the field called userName by looking for $_REQUEST["userName"].
5. Copy the form data into a PHP variable.
Now I have a variable called $userName that contains the data from the userName field in the previous form. Repeat this process for each form variable you want to retrieve from the form.
6. Print some new content.
The print statement in PHP prints text to the current spot in the HTML. In essence, it allows you to customize parts of the page on the fly. In this case, I want to add a paragraph with a greeting. Note that you should still strive for valid XHTML in your print statements.
7. Interpolate variables.
Notice how I added the $userName variable directly in the print statement. This technique is called interpolation. If PHP sees a term beginning with a dollar sign being printed, it knows it’s looking at a variable and replaces the variable name with its value.
8. End the PHP segment with ?>.
This symbol indicates the end of PHP processing and takes you back to XHTML mode.
Obviously this is a very cursory overview of PHP. It’s a complete language with a lot more potential than I’m showing in this basic example. If you want to know more, there are many topics on PHP that can take you farther (including some I have written.) Take a look at or my own site for much more information on the PHP language. You can also visit  to find more great topics packed with PHP info.

Sending Requests AJAX-Style

So far all the AJAX work in this topic has involved importing a preformatted HTML file. That’s a great use of AJAX, but the really exciting aspect of AJAX is how it tightens the relationship between the client and server. Figure 14-3 shows a page called AJAXtest.html, which uses a JavaScript function to call a PHP program and incorporates the results into the same page.
This page gets data from PHP with no form!
Figure 14-3:
This page gets data from PHP with no form!

Sending the data

The AJAX version of this program is interesting because it has no form, uses exactly the same PHP program as nameForm.html, and incorporates the results of the PHP program directly onto the same page. Begin by looking over the code:
This program uses a jQuery function to simulate a form. It generates its own virtual form and passes it directly to the PHP program. The PHP program then processes the form data and produces text results, which are available for JavaScript to handle directly. In essence, JavaScript and jQuery are directly managing the server request (rather than allowing the browser to do it automatically), so the programmer has more control over the process.

Here’s how it works:

1. Begin with an XHTML framework.
As always, XHTML forms the spine of any Web program. The XHTML here is quite simple: a heading and a div for output. Note that this example doesn’t include a form.
2. Include the jQuery library.
It’s possible to do AJAX without jQuery, but there’s not much reason to do that. The jQuery library makes life much easier and manages cross-browser issues to boot. You can also incorporate the jQuery UI and a theme if you choose, but they aren’t absolutely necessary.
3. Initialize as usual.
As soon as this program runs, it’s going to get data from the server. (In the next example, I show you how to make this process more interactive.) Set up an init() function in the normal way to handle immediate execution once the page has loaded.
4. Use the .get() function to set up an AJAX call.
jQuery has a number of interesting AJAX functions. The .ajax function is a very powerful tool for managing all kinds of AJAX requests, but jQuery also includes a number of utility functions that simplify particular kinds of requests. The .get() function used here sets up a request that looks to the server just like a form submitted with the get method. (Yep, there’s also a post() function that acts like a post form.)
5. Indicate the program to receive the request.
Typically your AJAX requests will specify a program, which should respond to the request. I’m using greetUser.php, the exact same program called by the simpler nameForm.html page.
6. Pass form data as a JSON object.
Encapsulate all the data you want to send to the program as a JSON object. (Check Chapter 5 for a refresher on JSON.) Typically this is a series of name/value pairs. In this example, I’m simply indicating a field named userName with the value .
7. Specify a callback function.
Normally you’ll want to do something with the results of an AJAX call. Use a callback function to indicate which function should execute when the AJAX call is completed. In this example, I call the processResult function as soon as the server has finished returning the form data.

Responding to the results

The greetUser.php program on the server will be run by the AJAXTest. html page. As far as greetUser.php knows, the data came from an ordinary form. This means I can use exactly the same program to work with the AJAX request that I used for the previous example. I don’t re-create the PHP code here because it hasn’t changed.
Back in the HTML, I need a function to process the results of the AJAX request after it has returned from the server. The processResult() function has been designated as the callback function, so take another look at that function:

This function is pretty simple with jQuery:

1. Accept two parameters.
AJAX callback functions accept two parameters. The first is a string containing whatever output was sent by the server (in this case, the greeting from processResult.php). The second parameter contains the text version of the HTTP status result. The status is useful for testing in case the AJAX request was unsuccessful.
2. Identify an output area.
I just make a jQuery node from the output div.
3. Pass the data to the output.
You’ll sometimes do more elaborate work with AJAX results, but for now my results are plain HTML that I can just copy straight to the div.

Building a More Interactive Form

Although AJAX can replace the form mechanism, it’s usually used in conjunction with ordinary forms to produce effects that would otherwise be difficult to achieve. For example, you might see a form that fills in some information for you by guessing at your data based on the first few characters of input. While it’s pretty easy to get real-time interaction on the client, it’s much more difficult to achieve this effect with server-side programs, because the server typically rebuilds the entire page at each pass. With AJAX, you can have the quick interaction of client-side programming along with the power of server-side programming. The interactiveForm.html demo, shown in Figure 14-4 shows a simple variation of this concept.
This example produces a complete round-trip to the server on each keystroke. That’s a lot of overkill for this simple example (which could be achieved with ordinary JavaScript) but imagine how powerful it could be. On each trip to the server, the program can check my name against a list of hundreds of names, and it can provide a hint as soon as it has enough letters. A server-side program can perform data searches against huge databases. You’ve probably seen this effect on pages you’ve used. You need a little more knowledge of server-side programming and databases than I can provide in this topic to achieve the entire effect, but you can clearly see from this example how the AJAX part works.
This page has a form. As the user types data in, that data is copied to the output.
Figure 14-4:
This page has a form. As the user types data in, that data is copied to the output.

Creating an AJAX form

You can create a form for AJAX use much like any other form. Here’s the full code for interactiveForm.html:
As you look over the XHTML code, you’ll notice that the form is set up more for JavaScript than server-side processing:
1. Include jQuery.
Have I mentioned how cool jQuery is?
2. The form action can be null.
This time you’re going to read the form in JavaScript and produce an AJAX request. The form action can (and should) be null, because you want JavaScript to submit the request, not the browser.
3. You don’t need to specify a transmission method in the form.
As far as the form is concerned, it’s a client-side form, so you don’t need to specify whether it is sent as a get or post request. (The AJAX call takes care of that.)
4. The input element has an id attribute but no name.
It can have a name, but it isn’t necessary, because the server won’t process it directly. You use the id attribute to get access to this element and then package your own JSON object to send to the PHP program through AJAX.
5. The event is called when the text field changes.
Often AJAX requests are meant to happen automatically, without requiring the user to press a submit button. To get this effect, you can use the onkeyup event handler. This event handler calls a function whenever the specified element has the focus and a key has been pressed and released.

Writing the JavaScript code

The JavaScript code is even simpler than normal. For one thing, this particular program doesn’t require an init() because nothing needs to be initialized. Of course, it’s likely that you’ll have a more elaborate project that might involve initialization (with jQuery UI elements, for example), but I kept this example simple for clarity.
The getGreeting() function extracts data from the form and uses it to send an AJAX request:
The getGreeting() function encapsulates the process of sending a form.
1. Extract the value of the userName field.
Create a jQuery node from the userName field and use the val() method to extract its value.
2. Store the value in a variable.
Store the value in a variable also called userName.
3. Use the get() method to set up an AJAX call.
The jQuery get() method simulates sending a form through the get method. (Of course, there’s also a post() method, if you prefer.)
4. Indicate the program that will respond to the data.
For this example, I use a variation of the greetUser.php program called simpleGreet.php. Look at the next section to see how AJAX can simplify your PHP code.
5. Send form fields as a JSON object.
The virtual form (which in this case is based on a real form) has one field called userName. I send it the value of the userName variable.
6. Specify a callback function.
Most AJAX calls have a callback function that should be executed when the data transmission is complete. In this example, I’m using the processResult function.

Processing the result

The processing is quite easy in this case because I simply want to copy the results of the PHP program directly to the output div:
The data parameter contains the text data returned from the AJAX call. I simply grab that text and pass it to the output div.

Simplifying PHP for AJAX

One of the nice things about AJAX is how it simplifies your server-side programming. If you look back at greetUser.php, you’ll see that it creates an entire XHTML page. Most PHP programs work that way, creating an entire page every time. However, because you’re using AJAX, the PHP result doesn’t have to be an entire Web page. The PHP can simply create a small snippet of HTML.

Take a look at simpleGreet.php and you’ll see it’s very stripped down:

Although this program works just like greetUser.php, it’s a lot simpler. All it needs to do is grab the user name and print it back out. The JavaScript function takes care of making the code go in the right place. Without AJAX, each PHP program has to re-create the entire page. When you’re using AJAX, the HTML page stays on the client, and JavaScript makes smaller calls to the server. The PHP is simpler, and the code transmission is generally smaller and faster, because there’s less repeated structural information.

Working with XML Data

Server-side work normally involves storage of data, as that’s one thing that’s easy to do on the server and difficult to do on the client. Data can be stored in many ways: plain text files, HTML, or XHTML, or in a specialized system called a relational database (a specialized program that allows you to store and query data efficiently). The database approach is most common because it’s incredibly powerful and flexible. Normally programmers use a PHP program to request information from a Web page, and then use this information to prepare a request for the database in a special language called SQL (Structured Query Language). The data request is passed to the database management system, which returns some kind of result set to the PHP program. The PHP program then typically builds an HTML page and passes the page back to the browser.
Data management is beyond the scope of this topic. See my Web site for more information about creating your own databases:
The process can be easier when you use AJAX because the PHP program doesn’t have to create an entire Web page. All that really needs to be passed back to the JavaScript program are the results of the data query. Normally, you do this using a special data format so the JavaScript program can easily manage the data.

Review of XML

The XML format has become an important tool for encapsulating data for transfer between the client and the server. If you’re using XHTML, you are already familiar with XML. XHTML is simply HTML following the stricter XML standard.
However, XML is much more than XHTML. It can actually be used to store any kind of data. For example, take a look at the following file (pets.xml):
If you look over pets.xml, you can see it looks a lot like HTML. HTML/ XHTML tags are very specific (only a few are legal) but XML tags can be anything as long as they follow a few simple (but familiar) rules:
1. Begin with a doctype.
Formal XML declarations often have doctypes as complex as the XHTML doctype definition, but basic XML data usually uses a much simpler definition:
Any time you make your own XML format (as I’m doing in this example), you can use this generic doctype.
2. Create a container for all elements.
The entire structure must have one container tag. I’m using pets as my container. If you don’t have a single container, your programs will often have trouble reading the XML data.
3. Build your basic data nodes.
In my simple example, each pet is contained inside a pet node. Each pet has the same data elements (but that isn’t a requirement).
4. Tags are case-sensitive.
Be consistent in your tag names. Use camel case and single words for each element.
5. You can add attributes.
You can add attributes to your XML elements just like the ones in XHTML. As in XHTML, attributes are name/value pairs separated by an equal sign (=), and the value must always be encased in quotes.
6. Nest elements as in XHTML.
Be careful to carefully nest elements inside each other like you do with XHTML.
You can get an XML file in a number of ways. Most databases can export data in XML format. More often, a PHP program reads data from a database and creates a long string of XML for output. For this simple introduction, I just wrote the XML file in a text editor and saved it as a file.
You can manipulate XML in the same way with JavaScript whether it comes directly from a file or is passed from a PHP program.

Manipulating XML with jQuery

XML data is actually familiar because you can use the tools you used to work with XHTML. Better, the jQuery functions normally used to extract elements from an XHTML page work on XML data with few changes. You can use all the standard jQuery selectors and tools to manage an XML file in the same way you use them to manage parts of an HTML page.
The readXML.html page featured in Figure 14-5 shows a JavaScript/jQuery program that reads the pets.xml file and does something interesting with the data. In this case, it extracts all the pet names and puts them in an unordered list. (See the following code.)
The pet names came from the XML file.
Figure 14-5:
The pet names came from the XML file.

Creating the HTML

Like most jQuery programs, the readXML.html page begins with a basic HTML framework. This one is especially simple: a heading and a list. The list has an id attribute (so it can be recognized through jQuery easily) and a single element (which will be replaced by data from the XML file).

Retrieving the data

The init() function sets up an AJAX request:

This function uses the get() function to request data:
1. Use the jQuery get() mechanism to set up the request.
Because I’m just requesting a static file (as opposed to a PHP program), the get() function is the best AJAX tool to use for setting up the request.
2. Specify the file or program.
Normally you call a PHP program to retrieve data, but for this example, I pull data straight from the pets.xml file. The get() mechanism can be used to retrieve plain text, HTML, or XML data. My program will be expecting XML data, so I should call an XML file or a program that produces XML output.
3. Set up a callback function.
When the AJAX is complete, specify a function to call. My example calls the processResult function after the AJAX transmission is complete.

Processing the results

The processResult() function accepts two parameters: data and textStatus.

The processResult() function does a few simple tasks:

1. Clear the output ul.
The output element is an unordered list (ul). Use its html() method to clear the default list item.
2. Make a jQuery node from the data.
The data (passed as a parameter) can be turned into a jQuery node. Use $(data) for this process.
3. Find each pet node.
Use the find() method to identify the pet nodes within the data.
4. Specify a command to operate on each element.
Use the each() method to specify you want to apply a function separately to each of the pet elements. Essentially, this creates a loop that calls the function once per element. The each mechanism is an example of a concept called functional programming. (Drop that little gem at your next computer science function.)
5. Run the printPetName function once for each element.
The printPetName is a callback function.

Printing out the pet name

The printPetName function will be called once for each pet element in the XML data. Within the function, the $(this) element refers to the current element as a jQuery node.
1. Retrieve the pet’s name.
Use the find() method to find the name element of the current pet node.
2. Pull the text from the node.
The name is still a jQuery object. To find the actual text, use the text() method.
3. Turn the text into a list item.
I just used string concatenation to convert the plain text of the pet name into a list item.
4. Append the pet name list item to the list.
The append() method is perfect for this task.
Of course, you can do more complex things with the data, but it’s just a matter of using jQuery to extract the data you want and then turning it into HTML output.

Working with JSON Data

A new data format called JSON is becoming increasingly important. In fact, some are suggesting that JSON will replace XML as the standard data transmission format for AJAX.
XML has been considered the standard way of working with data in AJAX (in fact, the X in AJAX stands for XML.) Although XML is easy for humans (and computer programs) to read, it’s a little verbose. All those ending tags can get a bit tedious and can add unnecessarily to the file size of the data block. Although XML isn’t difficult to work with on the client, it does take some getting used to.

Understanding JSON

AJAX programmers are beginning to turn to JSON (JavaScript Object Notation) as a data transfer mechanism. JSON is nothing more than the JavaScript object notation described in Chapter 5 and used throughout this topic. JSON has a number of very interesting advantages:
Data is sent in plain text. Like XML, JSON data can be sent in a plain text format that’s easy to transmit, read and interpret.
The data is already usable. Client programs are usually written in JavaScript. Because the data is already in a JavaScript format, it’s ready to use immediately, without the manipulation required by XML.
The data is a bit more compact than XML. JavaScript notation doesn’t have ending tags, so it’s a bit smaller. It can also be written to save even more space (at the cost of some readability) if needed.
Lots of languages can use it. Any language can send JSON data as a long string of text. You can then apply the JavaScript eval() function on the JSON data to turn it into a variable.
PHP now has native support for JSON. PHP version 5.2 and later supports the json_encode() function, which automatically converts a PHP array (even a very complex one) into a JSON object.
jQuery has a getJSON() method. This method works like the get() or post() methods, but it’s optimized to receive a JSON value.
If a program uses the eval() function to turn a result string to a JSON object, there’s a potential security hazard: Any code in the string is treated as JavaScript code, so bad guys could sneak some ugly code in there. Be sure you trust whoever is providing you the JSON data.
The pet data described in pets.xml looks like this when it’s organized as a
JSON variable:
Note that the data is a bit more compact in JSON format than it is in XML. Also, note that there’s no need for an overarching variable type (like pets in the XML data) because the entire entity is one variable (most likely called pets). JSON takes advantages of JavaScript’s flexibility when it comes to objects:
1. An object is encased in braces ({}).
The main object is denoted by a pair of braces.
2. The object consists of key/value pairs.
In my data, I used the animal name as the node key. Note that the key is a string value.
3. The contents of a node can be another node.
Each animal contains another JSON object, which holds the data about that animal. You can nest JSON nodes (like XML nodes), so they have the potential for complex data structures.
4. The entire element is one big variable.
JavaScript will see the entire element as one big JavaScript object that can be stored in a single variable. This makes it quite easy to work with JSON objects on the client.

Reading JSON data with jQuery

As you might expect, jQuery has some features for simplifying the (already easy) process of managing JSON data.
Figure 14-6 shows readJSON.html, a program that reads JSON data and returns the results in a nice format.
This program got the data from a JSON request.
Figure 14-6:
This program got the data from a JSON request.

Here’s the complete code of readJSON.html:


Managing the framework

The foundation of this program is the standard XTML and CSS. Here are the details:
1. Build a basic XHTML page.
Much of the work happens in JavaScript, so an hi and an output div are all you really need.
2. Put default text in the output div.
Put some kind of text in the output div. If the AJAX doesn’t work, you see this text. If the AJAX does work, the contents of the output div are replaced by a definition list.
3. Add CSS for a definition list.
I will print out each pet’s information as a definition list, but I don’t like the default formatting for <dl>. I add my own CSS to tighten up the appearance of the definitions. (I like the <dt> and <dd> on the same line of output.)

Retrieving the JSON data

The jQuery library has a special AJAX function for retrieving JSON data. The getJSON() function makes an AJAX call and expects JSON data in return.
It isn’t difficult to get JSON data with jQuery:
1. Set up the standard init() function.
In this example, I’m pulling the JSON data in as soon as the page has finished loading.
2. Use the getJSON() function. This tool gets JSON data from the server.
3. Pull data from pets.json.
Normally you make a request to a PHP program, which does some kind of database request and returns the results as a JSON object. For this simple example, I’m just grabbing data from a JSON file I wrote with a text editor.
4. Specify a callback function.
Like most AJAX methods, getJSON() allows you to specify a callback function that is triggered when the data has finished transferring to the client.

Processing the results

The data returned by a JSON request is already in a valid JavaScript format, so all you need is some for loops to extract the data. Here’s the process:
1. Create the callback function.
This function expects a data parameter (like most AJAX requests). In this case, the data object will contain a complete JSON object encapsulating all the data from the request.
2. Clear the output.
I will replace the output with a series of definition lists.
3. Step through each petName in the list.
This special form of for loop finds each element in a list. In this case, it gets each pet name found in the data element.
4. Extract the pet as a variable.
The special form of for loop doesn’t actually retrieve the pets, but the key associated with each pet. Use that pet name to find a pet and make it into a variable using an array lookup.
5. Build a heading with the pet’s name.
Surround the pet name with <h2> tags to make a heading and append this to the output.
6. Create a definition list for each pet.
Begin the list with a <dl> tag. Of course, you can use whichever formatting you prefer, but I like the definition list for this kind of name/value data.
7. Get the detail names from the pet.
The pet is itself a JSON object, so use another for loop to extract each of its detail names (animal, breed, and note).
8. Set the detail name as the definition term.
Surround each detail name with a <dt></dt> pair.
9. Surround the definition value with <dd><dd>.
This step provides appropriate formatting to the definition value.
10. Close up the definition list.
After the inner for loop is complete, you’re done describing one pet, so close up the definition list.
As you can see, JSON is pretty easy to work with, so it’s becoming much more common as a data transfer mechanism.

Next post:

Previous post: