How to Auto-Fill City/State from Zipcode on your Forms

Have you ever been filling out a form on a website when you realized your city and state had already been populated for you? It used to be amazing but now it’s just the standard. If your website doesn’t auto-populate the city and state after someone enters the zip, you’re falling behind. Luckily it’s super easy to do.

Why would you want to do this?

  • It makes less fields that your customer has to fill out. Less fields = more conversions
  • It increases data quality and consistency. No more misspellings or different CASES in your list
  • Everyone else is doing it. Seriously, this has been popular since 2001.


autofill

Here’s how, in 3 easy steps:

  1. Acquire a Zipcode Location database. Here’s one that we offer that provides easy zip to city/state lookup.
  2. Write a server-side script that will lookup the city and state given the zip as a url parameter. This will be used in an AJAX call. Sample script is provided below.
  3. Put a javascript snippet on your form that will call that script once the zip code has been filled out. We’ve provided an example of this script below too.

Here’s an example server-site lookup script (written in PHP, using a MySQL database)

<?php
//you'll have to replace your credentials here
$mysqldatabase="XXXX";
$mysqluser="XXXX";
$mysqlpassword="XXXXX";

//connect to db
$DBCONN=mysql_connect("localhost",$mysqluser,$mysqlpassword);
if(!$DBCONN) die("Couldn't connect to MySQL Server.");

//perform lookup
$query = "SELECT city, state_abbr FROM EasyDbsZipcodeLocations WHERE zip=".mysql_real_escape_string($_GET['zip']);
$result=mysql_db_query($mysqldatabase, $query) or die(mysql_error());

//print out results
$row = mysql_fetch_array($result);
echo $row['city'].",".$row['state_abbr'];
?>

Here’s an example client-side AJAX script (Javascript)

<script>
var ajax = getHTTPObject();

function getHTTPObject()
{
	var xmlhttp;
	if (window.XMLHttpRequest) {
	  // code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
	  // code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	} else {
	  //alert("Your browser does not support XMLHTTP!");
	}
	return xmlhttp;
}

function updateCityState()
{
	if (ajax)
	{
		var zipValue = document.getElementById("zipcode").value;
		if(zipValue)
		{
			var url = "path/to/your/script/get_city_state.php";
			var param = "?zip=" + escape(zipValue);

			ajax.open("GET", url + param, true);
			ajax.onreadystatechange = handleAjax;
			ajax.send(null);
		}
	}
}
function handleAjax()
{
	if (ajax.readyState == 4)
	{
		citystatearr = ajax.responseText.split(",");

		var city = document.getElementById('city');
		var state = document.getElementById('state');

		city.value = citystatearr[0];
		state.value = citystatearr[1];
	}
}

//then on your form:
// 1: Update zip field to call onblur="updateCityState();"
// 2: Make sure your zip, city, and state fields have ID's with those names
</script>

That’s all you need! Awesome!

Check out a live, working demo here.

Everyone else is already doing this so if you’re not, your competitors are! Feel free to post any questions in the comments below.

Having trouble with your database install? Try downloading an Easy To Install Database from EasyDbs!

8 Thoughts on “How to Auto-Fill City/State from Zipcode on your Forms

  1. DatabaseGuru on February 18, 2013 at 3:37 pm said:

    Note that the above script returns the 2-character state abbreviation. If you want the full state name, change the field name to ‘state’ in the PHP database script

  2. Hi,

    Looks like it should work… But for some reason I can’t get this to work…

  3. DatabaseGuru on April 9, 2013 at 2:23 pm said:

    Hi Rob – I’m happy to help. What part are you having trouble with?

  4. yogesh on July 21, 2014 at 10:06 am said:

    In above code.I have not understood this line

    var url = “path/to/your/script/get_city_state.php”;

    and both Ajax and php code should be in one page or we have to make it different

  5. Unless your users reliably populate the ZIP+4 code always, you will never get the city to pop up reliably as there is no 1:1 relationship between ZIP and city. States are always reliable.

  6. Barsigo on December 8, 2014 at 2:12 pm said:

    I will like to direct what I populate to another page. I would like to populate information/data on current form and use it in another form.
    eg

    Name: Tony Carson
    From: (fetch town from populated field)

    Then I will submit

  7. Kevin on July 23, 2015 at 7:15 pm said:

    Does this work for WordPress forms?

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation