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 ...

Get Learning JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.