Using AJAX to get city and state from zip code

This is something that I wrote a few years ago when I first started using AJAX type calls in my programs. It will allow you to enter a zip code, either 5 or 9 digit, and will load the city into a text field and state into a dropdown. If the city field is blank then nothing is done.

First we need a database of zip codes. While there are probably hundreds of companies selling zip code databases, I did manage to find one place where they give away a copy for free. Once you download the text file of zip codes you’ll need to import it into a MySQL database with fields city, state, and zip. For now I’ll leave that up to you, but I may add a post later to explain how it’s done.

Now that we have the database of zip codes we need the PHP script that handles the backend of the AJAX call. Copy and paste the following code into a file called zipcode.php, changing the database settings in lines 7-11 to match your server.

PHP:
  1. <?php
  2.  
  3. /*  Returns the city and state in delimited format based on a zip
  4.     code sent as query string ?zipcode=#####
  5.     */
  6.    
  7. $dbhost = ‘localhost’;
  8. $dbusername = ‘db_user’;
  9. $dbpass = ‘password’;
  10. $db_name = ‘db_name’;
  11. $db_table = ‘db_table’;
  12.  
  13. /*  Set an error state as default
  14.     */
  15. $returnval = “Error”;
  16.  
  17. $zipcode = $_GET[‘zip’];
  18. if (strlen($zipcode)>5)
  19.     {
  20.     $zipcode = substr($zipcode, 0, 5);
  21.     }
  22. if (strlen($zipcode)!=5)
  23.     {
  24.     die ($returnval);
  25.     }
  26.  
  27. /*  Open the database and recordset
  28.     */
  29. $query = “SELECT * FROM {$db_table} WHERE zip=’{$zipcode}’”;
  30. $conn = mysql_connect($dbhost, $dbusername, $dbpass) or die(“Cannot connect to MySQL database server:<br>”.mysql_error());
  31. $db = mysql_select_db($db_name, $conn) or die(“Cannot open database:<br>”.mysql_error($conn));
  32. $resultval = mysql_query($query) or die(“Cannot run query:<br><b>Query:</b> “.$query.“<br>”.mysql_error($conn));
  33.  
  34. $rowcount = mysql_num_rows($resultval);
  35. if ($rowcount==1)
  36. /*  Echo out the string
  37.     */
  38.     {
  39.     $row = mysql_fetch_array($resultval);
  40.     $returnval = $row[‘zip’].“|”.ucwords(strtolower($row[‘city’])).“|”.$row[’state’];
  41.     }
  42. else
  43. /*  Don’t need to do anything, the error value is already set above
  44.     */
  45.     {
  46.     }
  47.  
  48. echo $returnval;
  49. ?>

Next we need to make sure our page is setup correctly. The following HTML is a snippet of what needs to be on the page.

HTML:
  1. City <input type=“text” name=“txtCity” id=“txtCity”><br>
  2. State
  3. <select name=“cboState” id=“cboState”>
  4. <option value=“AK”>Alaska</option>
  5. <option value=“AL”>Alabama</option>
  6. <!–Do all 50–>
  7. <option value=“WY”>Wyoming</option>
  8. </select>
  9. Zip <input type=“text” name=“txtZip” id=“txtZip” onblur=“fillcitystate(this);”>

Lines 4-7 should really have all 50 state codes. I’ll copy a list of the 50 abbreviations at the end of this article.

fillcitystate(this) is the AJAX call that actually gets the information, and we’ll do that next.

JavaScript:
  1. function fillcitystate(controlname)
  2.     {
  3.     /*  Check to make sure there is not already something entered
  4.         for city.  If there is, just exit out of this script
  5.         */
  6.     if (document.getElementById(“txtCity”).value!=“”)
  7.         {
  8.         return false;
  9.         }
  10.  
  11.     var zipstring = “”;
  12.     xmlhttp = new XMLHttpRequest();
  13.    
  14.     xmlhttp.open(“GET”, “/zipcode.php?zip=” + controlname.value, true);
  15.     xmlhttp.onreadystatechange=function()
  16.         {
  17.         if (xmlhttp.readyState==4)
  18.             {
  19.             var zipstring = xmlhttp.responseText;
  20.             if (zipstring!=“Error”)
  21.                 {
  22.  
  23.                 var ziparray = zipstring.split(“|”);
  24.                 document.getElementById(“txtCity”).value = ziparray[1];
  25.                 document.getElementById(“cboState”).value = ziparray[2];
  26.                 }
  27.             }
  28.         }
  29.     xmlhttp.send(null);
  30.  
  31.     }

Lines 6-9 check to make sure that there isn’t already a city entered. If there is then the script exits without any action.

You’ll need to edit line 14 to match the path to where you saved your zipcode.php file.

State Codes
AK, AL, AR, AZ, CA, CO, CT, DC, DE, FL, GA, HI, IA, ID, IL, IN, KS, KY, LA, MA, MD, ME, MH, MI, MN, MO, MS, MT, ND, NE, NH, NJ, NV, NY, OH, OK, OR, PA, RI, SC, SD, TN, TX, UT, VA, VT, WA, WI, WV, WY.

Question, Comments...

Do you have more questions. Please either leave a comment below or join us in our new forum.

Leave a Reply