……………………………………………….Expertise in .NET Technologies

Dynamically populating city and state from ZIP codes using AJAX and WebServices

Posted by Ravi Varma Thumati on May 7, 2009



Sick of hearing about web services yet? How about AJAX? What if I told you that you could use AJAX (JavaScript and DHTML) to request the XML output of an ASP.NET web service and display the data without reloading the page? Interested yet? As you can imagine, this solution has many applications. It allows you to speed up your web application by not forcing the user to reload a page every time they request information, while at the same time only loading data when it is requested. As well as adding speed and function to your current tasks, you may find yourself inventing new ways to make your web applications more user friendly, that were just not feasible using server side technologies.


In the example below, I will investigate building a form that auto completes the city and state information after the user types in their ZIP code. There are two essential parts to this project. First being the creation of a web service that will return a city and state given its ZIP code, and the second, an HTML page that uses JavaScript to request XML from the web service.

Using the code

Step 1: Creating the web service.

If you’re not familiar with web services, you may be overwhelmed by all the hype that surrounds them. In actuality, people spend a lot more time talking about web services than actually coding them. This is because ASP.NET makes it very easy to build web services quickly without introducing an entirely new methodology to do so.

The first step to building this web service was finding the ZIP code data. I have included in the ZIP package a CSV file that contains 98% of the ZIP codes in the United States based on the 2003 census data. Once you successfully download and extract this CSV file, you will simply need to import the data into your SQL Server and you will be ready to go.

Next you will need to build your asmx file. In this case, our web service needs to accept an integer using “get”, make a simple SQL query to the database, and return the city and state. To accomplish this, we use the following code: 

<%@ WebService %>
Imports System.Web.Services
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration 
<WebService(Namespace:="")> _
           Public Class ZipService : Inherits WebService 
  Private Function GetDataSet(strSQL as String) as DataSet
    Dim myConnection as New SqlConnection("Persist Security Info" & _ 
        "=False;Data Source=Server;Initial Catalog=db;" & _ 
        "User ;Password=XX ;")
    Dim myCommand as New SqlCommand(strSQL, myConnection)
    Dim myDataAdapter as New SqlDataAdapter()
    myDataAdapter.SelectCommand = myCommand
    Dim myDataSet as New DataSet()
       Return myDataSet 
    End Function
     <WebMethod()> Public Function GetZip(Z As System.Single) as DataSet
    Return GetDataSet("Select city,state from zipcode where zip = "  Z)
  End Function
End Class

To see a demonstration of this code in action, take a look at the web service running on my web server.

Step 2: Creating the AJAX file.

Now that you have your web service built, we need to put it to use. In this case, the challenge was to auto-complete form fields based on ZIP code data. After the user types in a ZIP code, we need to trigger an event to invoke a client side XMLHttpRequest, aggregate that data, and fill in the other form fields. We will start by looking at the JavaScript functions below:

  var req;
  var response;
  var city;
  var state;
  function loadXMLDoc(url) {
      // branch for native XMLHttpRequest object
      if (window.XMLHttpRequest) {
          req = new XMLHttpRequest();
          req.onreadystatechange = processReqChange;
"GET", url, true);
      // branch for IE/Windows ActiveX version
      } else if (window.ActiveXObject) {
          isIE = true;
          req = new ActiveXObject("Microsoft.XMLHTTP");
          if (req) {
              req.onreadystatechange = processReqChange;
    "GET", url, true);
  function processReqChange() {
      if (req.readyState == 4) {
          if (req.status == 200) {
  document.forms[0].output.value  = req.responseText
  response  = req.responseXML.documentElement;
  city = response.getElementsByTagName('city')[0];
  state = response.getElementsByTagName('state')[0];
  document.forms[0].city.value = city
  document.forms[0].state.value = state
          } else {
              alert("Please enter a valid zip code:\n" +
  function loadxml(form) {
  loadXMLDoc('' + 
     'zipcodes.asmx/GetZip?z=' + document.forms[0].zipcode.value);

As you can see, we are passing the URL of our web service loadXMLDoc function and defining the nodes to display the data. Now all that is left to do is invoke the script. In this case, we will use the OnBlur event like so:

<input type = "text" name = "zipcode" 
            onblur = "loadxml(this.form);" />

One Response to “Dynamically populating city and state from ZIP codes using AJAX and WebServices”

  1. blagues said

    This is a perfect post. I like your writing style. Will look around your website

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: