Приглашаем посетить
Пушкин (pushkin-lit.ru)

Hack 20. Tame Ajax with JSON

Previous
Table of Contents
Next

Hack 20. Tame Ajax with JSON

Hack 20. Tame Ajax with JSON Hack 20. Tame Ajax with JSON

Use JSON to make Ajax easier to implement.

The combination of DHTML, CSS, and XML SOAP or REST requests from the browser is known as Ajax. Ajax is a great way to create dynamic web interfaces without ever requiring a page fetch. Largely centered on the JavaScript in a page requesting HTTP transfers, Ajax-enabled applications often use DHTML to change the HTML of a page, creating dynamic applications that feel like client-side apps. Typically, JavaScript contacts a PHP or Perl script on a server and then interprets the returned text, which is most often XML.

Parsing the XML isn't rocket science, but it isn't a walk in the park, either. That's why developers created the JSON (http://json.org/) library, which makes it easy for JavaScript to interpret the response from the server. This hack uses the JSON PEAR module to format data coming out of the server, and shows how that JSON code is consumed in the browser.

3.11.1. The Code

Save the code shown in Example 3-13 as getdata.php.

Example 3-13. PHP responding to an Ajax request
<?php
require( 'JSON.php' );

$records = array();
$records []= array( 'id' => 1, 'last' => 'Herrington', 'first' => 'Jack' );
$records []= array( 'id' => 2, 'last' => 'Herrington', 'first' => 'Megan' );
$records []= array( 'id' => 3, 'last' => 'Herrington', 'first' => 'Lori' );

$json = new JSON();
echo( $json->encode( $records ) );
?>

Now create a test page; I've named mine index.php (see Example 3-14).

Example 3-14. A simple example of Ajax making a request and updating the page with the returned data
<html>
<head>
<title>JSON Test</title>
<script>
var req;

function processReqChange()
{
  if ( req.readyState == 4 && req.status == 200 )
  {
	var rows = eval( req.responseText );

	var html = "<table>";
	for( r in rows )
	{
		html += "<tr>";
		html += "<td>"+rows[r].id+"</td>";
		html += "<td>"+rows[r].first+"</td>";
		html += "<td>"+rows[r].last+"</td>";
		html += "</tr>";
	}
	html += "</table>";

	document.getElementById( "data" ).innerHTML = html;
  }
}

function getNames()
{
  if (typeof window.ActiveXObject != 'undefined' )
  {
	req = new ActiveXObject("Microsoft.XMLHTTP");
	req.onreadystatechange = processReqChange;
  }
  else
  {
	req = new XMLHttpRequest();
	req.onload = processReqChange;
  }
  try {
	req.open( 'GET', 'http://localhost:1222/json/getdata.php', true );
  } catch( e ) {
	alert( e );
  }
  req.send("");
}
</script>
</head>
<body>
<div id="data">

</div>
<script>
getNames();
</script>
</body>
</html>

The index.php page calls getNames(), a JavaScript method that creates an HttpRequest object and points it at the getdata.php page. That script packs up some data and returns it using the JSON module. The script (back in index.php) then unpacks this data using the eval function. With the data unraveled, it's just a matter of putting some HTML together and setting the innerHTML of the data <div> tag.

Figure 3-15 shows the Ajax session between index.php and getdata.php in this hack. The browser, symbolized here by the computer, requests the index.php page. The index.php page then makes an HTTP request to getdata.php, which in turn returns the JSON-encoded data (avoiding the need for index.php to do any XML parsing).

Figure 3-15. A JSON-based Ajax session
Hack 20. Tame Ajax with JSON


3.11.2. Running the Hack

Upload the index.php and getpage.php pages to the server. Then surf over to the index.php page in your browser. You should see something like Figure 3-16.

JSON does make it easier to program Ajax with JavaScript, but that ease comes at a price. Because the web server now returns JSON code instead of XML, your PHP scripts will be harder for other languages to use. Ideally, the getdata.php page should vend the data in either XML or JSON, depending on what the client wants to see.

Figure 3-16. The JSON test page
Hack 20. Tame Ajax with JSON



Previous
Table of Contents
Next