Ajax: It's not only code

Ajax works outside the page but safely inside the JavaScript sandbox.

1 2 3 4 5 6 Page 4
Page 4 of 6

Hello Ajax World!

You can use Ajax to populate a drop-down box based on a selection in another box. It’s an on-demand solution that limits how often a database is accessed. It’s also a very simple Ajax effect to create.

Example 13-1 contains the web page, including the script used to make the Ajax server call. The page also contains a form with two select elements: one populated with two states, the other empty.

Example 13-1. First Ajax application

<!DOCTYPE html PUBLIC "-//W3C//DTD 
  XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/
  xhtml1-transitional.dtd">
<html>
<head>
<title>Hello Ajax World</title>
<meta http-equiv="Content-Type" 
  content="text/html; 
  charset=utf-8" />

<style type="text/css">
div.elem { margin: 20px; }
</style>

<script 
  type="text/javascript">
//<![CDATA[

var xmlhttp = false;
if (window.XMLHttpRequest)
{
   xmlhttp = new 
     XMLHttpRequest( );
   xmlhttp.overrideMimeType
    ('text/xml');
} 
else if (window.ActiveXObject)
{
   xmlhttp = new 
    ActiveXObject
    ("Microsoft.XMLHTTP");
}

function populateList() {
 var state = 
 document.forms[0].elements[0].value;
 var url = 
   'ajax.php?state=' + state;
   xmlhttp.open('GET', url, true);
   xmlhttp.onreadystatechange = 
    getCities;
   xmlhttp.send(null);

}

function getCities() {
   if(xmlhttp.readyState == 4 
     && xmlhttp.status == 200)
   {
      document.
       getElementById('cities').innerHTML
       = "<select>" 
       + xmlhttp.responseText 
       + "</select>";
   } 
   else 
   {
      document.
       getElementById('cities').innerHTML
       = 'Error: preSearch Failed!';
   }
}
//]]>
</script>

</head>
<body>

<h3>Select State:</h3>
<form action="ajax.php" method="get">
<div class="elem">
<select onchange="populateList(  )">
<option value="CA">California</option>
<option value="MO">Missouri</option>
<option value="WA">Washington</option>
<option value="ID">Idaho</option>
</select>
</div>
<h3>Cities:</h3>
<div class="elem" id="cities">
<select>
</select>
</div>
</form>

</body>
</html>

Figure 13-1. Web page before Ajax call

Example 13-1

Example 13-1

First Ajax application

In the code, the second select is surrounded by a DIV identified by cities. When the results are returned, this element’s innerHTML is replaced with the new contents: either a select with the options returned by the web service, or an error message. Figure 13-1 shows the page before the Ajax call.

1 2 3 4 5 6 Page 4
Page 4 of 6
  
Shop Tech Products at Amazon