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

   This HTML scipt demonstrates the use of the AJAX pattern for interactive web pages using 
       XMLHTTPRequest to fetch data from the server
       XML parsing using DOM access methods
       DOM updating using innerHTML

   Based on example in http://www.webpasties.com/xmlHttpRequest/ by Bill Bercik

   Modified by Chris Wallace , Aug 2005
       fail result returned as XML 
       onSubmit trapped to ensure a simple return will trigger conversion as well as focus loss
       page updated using innerHTML

-->

<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?zipcode="; // The server-side script
function updateCityState() {
  if (http.readyState == 4) {
       // Use the XML DOM to unpack the city and state data 
      var xmlDocument = http.responseXML; 
      var result = xmlDocument.getElementsByTagName('result').item(0).firstChild.data;
      if (result =='succeed') {
         var city = xmlDocument.getElementsByTagName('city').item(0).firstChild.data;
         var state = xmlDocument.getElementsByTagName('state').item(0).firstChild.data;
         document.getElementById('result').innerHTML = '<h3>' + city + ', ' + state + '</h3>';
      }
      else {
         document.getElementById('result').innerHTML = '<h3>No such Zip Code </h3>';
      }    
      isWorking = false;
  }
}

var isWorking = false;

/* this flag is used to ensure that one request finishes before another starts - there are
   other ways to check this 

*/

function getCityState() {
  if (!isWorking && http) {
    var zipValue = document.getElementById("zip").value;
    http.open("GET", url + escape(zipValue), true);
    http.onreadystatechange = updateCityState;  
          // this sets the calls back function to be invoked when a response from the HTTP request is returned
    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();
      xmlhttp.overrideMimeType("text/xml"); 
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>

</head>
<body>
<h1>US Zipcode decoder</h1>
<form onSubmit="getCityState(); return false">
  <p>
  ZIP code:
  <input type="text" size="5" name="zip" id="zip" onblur="getCityState();" /> e.g. 95472
  </p>
  <div id="result">
  </div>
</form>
</body>
</html>