Ajax

Introduction

Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.

Like DHTML and LAMP, Ajax is not a technology in itself, but a group of technologies. Ajax uses a combination of HTML and CSS to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads. Server-side pages are contained in PHP or server-side scripting.

The term Ajax has come to represent a broad group of web technologies that can be used to implement a web application that communicates with a server in the background, without interfering with the current state of the page.

  • Updating one portion of a page - Such as a price indicator as a customer selects among various option on a form. This saves server overhead and is faster for the user.
  • Getting information from the server - Such as pulling a specific record.

Sample

https://wiki.cse.buffalo.edu/ajax

This demo starts with a PHP script that parses and XML file containing metadata about music CDs.

Example:

<?xml version="1.0" encoding="ISO-8859-1"?>
<CATALOG>
        <CD>
                <TITLE>Empire Burlesque</TITLE>
                <ARTIST>Bob Dylan</ARTIST>
                <COUNTRY>USA</COUNTRY>
                <COMPANY>Columbia</COMPANY>
                <PRICE>10.90</PRICE>
                <YEAR>1985</YEAR>
        </CD>
        <CD>
                <TITLE>Hide your heart</TITLE>
                <ARTIST>Bonnie Tyler</ARTIST>
                <COUNTRY>UK</COUNTRY>
                <COMPANY>CBS Records</COMPANY>
                <PRICE>9.90</PRICE>
                <YEAR>1988</YEAR>
        </CD>

Building a drop down

in index.php:

$xml = file_get_contents('./cd_catalog.xml');
$sxe = new SimpleXMLElement($xml);
$options = array();
foreach($sxe->CD as $CD) {
  $options[] = $CD;
}

This reads the XML and creates an array containing all the data in the file, structured as the XML tags are.

  <select name="artist" id="cd-selector">
<?php foreach($options as $key => $option): ?>
    <option value="<?php echo $key ?>"><?php echo (string) $option->ARTIST; ?></option>
<?php endforeach; ?>
  </select>

This creates an html dropdown box populated with all the album titles.

The HTML also contains a <div> with id="cd-details" and

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

Which Loads the jQuery Javascript Library

jQuery

The rest of the work is done in selectcd.js:

jQuery(function(){
  jQuery('#cd-selector').change(function(){
    jQuery.post('index.php', { artist: jQuery(this).val() }, function(data){
      jQuery('#cd-details').html(data);
    });
  });
});

Breaking this down: jQuery('#cd-selector').change(... This grabs the #cd-selector drop down box and assigns a change function to it, similarly to the onChange HTML attribute. The anonymous function assigned is passed directly as an attribute: function(){
jQuery.post('index.php', { artist: jQuery(this).val() },

jQuery.post sends a script (index.php) a key/value pair (artist=the value of the drop down) and passes the result to another anonymous function:

function(data){
   jQuery('#cd-details').html(data);
}

jQuery('#cd-details') grabs the #cd-details <div> the .html(data) function sets the contents of that argument to data (which was given by index.php)

Back to Server Side

if (isset($_REQUEST['artist'])) {
  # artists only have 1 CD
  $cd = $options[$_REQUEST['artist']];
?>
  <dl>
    <dt><?php echo (string) $cd->TITLE; ?></dt>
    <dd><span>Artist:</span> <?php echo (string) $cd->ARTIST; ?></dd>
    <dd><span>Country:</span> <?php echo (string) $cd->COUNTRY; ?></dd>
    <dd><span>Company:</span> <?php echo (string) $cd->COMPANY; ?></dd>
    <dd><span>Price:</span> $<?php echo (string) $cd->PRICE; ?></dd>
    <dd><span>Year:</span> <?php echo (string) $cd->YEAR; ?></dd>
  </dl>
<?php
  exit;
}
?>

This PHP snippet interrupts the display of the drop down box, and instead outputs a definition list containing the metadata for the requested CD.

Notes

Upgrades

  1. The data could be pulled from a mySQL database instead of an XML file.
  2. The PHP script could pass XML to the javascript page, the javascript would handle the rendering of the raw data.

References

  1. http://en.wikipedia.org/wiki/Ajax_%28programming%29
  2. http://us2.php.net/simplexml - SimpleXMLElement PHP XML Parsing
  3. http://docs.jquery.com/Main_Page - jQuery Documentation
  4. http://marcgrabanski.com/article/jquery-makes-parsing-xml-easy - jQuery XML Parsing