Tue 12 Jun 2012
this site http://federalgovernmentzipcodes.us/ has a database of US zipcodes to cities. there is a many cities to zip relationship.
what if you wanted a nifty form that took a zip and then populated a dropdown box with cities matching that zip?
first, let’s get the database file (csv) into a usable form. a database would be nice, but just for kicks, lets make a serialized array. it’s fast enough. this script will take that csv and create a one to many array serialized into a neat file:
$filename='free-zipcode-database.csv'; $handle = fopen($filename, 'r'); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { if (!isset($zipCodes[$data[1]])) { $zipCodes[$data[1]]=$data[3]; } else { $zipCodes[$data[1]]=$zipCodes[$data[1]]."|".$data[3]; } } fclose($handle); $serialZipCodes=serialize($zipCodes); $handle = fopen('serialzips.txt', 'w'); fwrite($handle, $serialZipCodes); fclose($handle);
now that we have our data inside serialzips.txt, let’s create a lookup script that will take a zip and return a JSON encoded array of cities
$filename='serialzips.txt'; $blob=file_get_contents($filename); $zipCodes=unserialize($blob); $zipArray=array_unique(explode('|',$zipCodes[$_REQUEST['zip']])); echo(json_encode($zipArray));
and now for a bit of HTML to exercise the lookup script when the user types in a zip code into a text field:
<head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> var lastzip=''; function cityLookup() { $('#zip').keyup(function() { var zip=document.getElementById("zip").value; if (lastzip===zip) return; if (zip.length<5) return; lastzip=zip; $('#spinner').show(); $.getJSON("lookup.php?zip="+escape(zip), function(data){ $('#mySelect').empty(); $.each(data, function(index, text) { if (text!='') $('#mySelect').append( $('<option></option>').val(index).html(text) ); $("#mySelect").val($("#mySelect option:first").val()); $('#spinner').hide(); }); }); }); } $(document).ready(function(){ cityLookup(); $("#zip").keypress(function(){ cityLookup(); }); }); </script> </head> <body> <p> <b>Instructions</b>: type a zip code, and the city dropdown will populate with possible cities </p> <form> <table cellspacing="5" cellpadding="5"> <tr> <td> <b>Zip Code: </b><input type="text" id="zip" value=""/> </td> <td><b>City: </b><select id="mySelect"></select> </td> <td><img style="display: none" id="spinner" src="spinner.gif" /></td> </tr> </table> </form> </body>
Enjoy!
Ick, variables in the global namespace. Wrap it with a closure, like this:
(function($){
var lastzip = ”;
…
})(jQuery);
And document.getElementById(“zip”).value? Why not $(‘#zip’).val() or even better, $(this).val().
well said, Mr. S, well said!