Webmaster Web Tools
Easy to Use Web Tools
IM Status Buttons, Flickr RSS Slideshows
RSS Scrollers, Podcast RSS and more.
www.webpasties.com

Back to WebPasties
Back to Step #6

Step #7 - Room for Improvement

In our haste to get our code up and running, we have neglected the following scenarios:

  1. Invalid ZIP codes are typed in.
  2. The visitor's browser does not support the XMLHttpRequest object.
  3. A request is made before the last request has completed.

Lets make ourselves feel all warm and fuzzy inside and add the highlighted code below to our HTML file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

<title>ZIP Code to City and State using XmlHttpRequest</title>

<script language="javascript"  type="text/javascript">

var url = "getCityState.php?param="; // The server-side script

function handleHttpResponse() {

  if (http.readyState == 4) {

    
if (http.responseText.indexOf('invalid') == -1) {
// Split the comma delimited response into an array results = http.responseText.split(","); document.getElementById('city').value = results[0]; document.getElementById('state').value = results[1];
isWorking = false;
}
} }
var isWorking = false;
function updateCityState() {
if (!isWorking && http) {
var zipValue = document.getElementById("zip").value; http.open("GET", url + escape(zipValue), true); http.onreadystatechange = handleHttpResponse;
isWorking = true;
http.send(null);
}
}
function getHTTPObject() { var xmlhttp; /*@cc_on @if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; } } return xmlhttp; } var http = getHTTPObject(); // We create the HTTP Object </script> </head> <body> <form action="post"> <p> ZIP code: <input type="text" size="5" name="zip" id="zip" onblur="updateCityState();" /> </p> City: <input type="text" name="city" id="city" /> State: <input type="text" size="2" name="state" id="state" /> </form> </body> </html>

Step #7 Source Code



To Step #8 - What about the XML?

-->