Click here to Skip to main content
15,867,308 members
Articles / Web Development / HTML
Article

Dynamically populating city and state from ZIP codes using AJAX and ASP.NET web services

Rate me:
Please Sign up or sign in to vote.
4.61/5 (28 votes)
4 Aug 20053 min read 153.5K   1.1K   79   26
Dynamically populating city and state from ZIP codes using AJAX and ASP.NET web services.

Sample Image

Introduction

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.

Background

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 your 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:

VB.NET
<%@ WebService Language="VB" Class="ZipService" %>
Imports System.Web.Services
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

<WebService(Namespace:="http://www.aprogrammersjournal.com")> _
           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 ID=XX ;Password=XX ;")
    Dim myCommand as New SqlCommand(strSQL, myConnection)
    myConnection.Open()

    Dim myDataAdapter as New SqlDataAdapter()
    myDataAdapter.SelectCommand = myCommand

    Dim myDataSet as New DataSet()
    myDataAdapter.Fill(myDataSet)
    myConnection.Close()
  
       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. View Web Service.

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:

JavaScript
<script language="Javascript">

 <!--

 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;
         req.open("GET", url, true);
         req.send(null);
     // branch for IE/Windows ActiveX version
     } else if (window.ActiveXObject) {
         isIE = true;
         req = new ActiveXObject("Microsoft.XMLHTTP");
         if (req) {
             req.onreadystatechange = processReqChange;
             req.open("GET", url, true);
             req.send();
         }
     }
 }

 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].firstChild.data;
 state = response.getElementsByTagName('state')[0].firstChild.data;
 document.forms[0].city.value = city
 document.forms[0].state.value = state
         } else {
             alert("Please enter a valid zip code:\n" +
                 req.statusText);
         }
     }
 }

 function loadxml(form) {
 loadXMLDoc('http://www.aprogrammersjournal.com/' +
    'zipcodes.asmx/GetZip?z=' + document.forms[0].zipcode.value);
 }

 //-->

 </script>

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:

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

Points of Interest

Why HTML? Some of you may be familiar with the great client side scripting capabilities of ASP.NET and wonder why I would choose standard JavaScript over ASP.NET. The bottom line is that even though my web service is written in ASP.NET, my client can be deployed on any server no matter what technology it is using. Also, using this method takes a good amount of load off of your web server because you are basically pushing all of the work on the client. The client computer invokes the web service, parses the XML, and returns the result to the user. The server only had to serve up a small HTML file which takes almost no resources to complete.

History

  • 8/4/2005 - Released.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
For more articles please visit my website:
http://www.aprogrammersjournal.com

A Programmers Journal
RSS

Comments and Discussions

 
SuggestionASP.Net 4.0 - A potentially dangerous Request.Form value.... Pin
TnNytehawk10-Apr-12 2:48
TnNytehawk10-Apr-12 2:48 
QuestionSetup Pin
ejc679-May-11 14:38
ejc679-May-11 14:38 
QuestionInternal Server Error 500 Pin
RTonerII3-Sep-09 12:55
RTonerII3-Sep-09 12:55 
QuestionProblem with the program Please Help! Pin
WeilerM23-Feb-09 6:23
WeilerM23-Feb-09 6:23 
GeneralYour Demo Pin
MMRR11-Dec-06 9:36
MMRR11-Dec-06 9:36 
GeneralRe: Your Demo Pin
Jason Witty2-Mar-08 12:08
Jason Witty2-Mar-08 12:08 
QuestionASPX Page Pin
MMRR8-Dec-06 3:07
MMRR8-Dec-06 3:07 
GeneralRe: ASPX Page Pin
Jason Witty2-Mar-08 12:07
Jason Witty2-Mar-08 12:07 
Generalgetting XMLHttpRequest.Statustext as Internal Server Error Pin
Athena62719-Apr-06 1:09
Athena62719-Apr-06 1:09 
GeneralRe: getting XMLHttpRequest.Statustext as Internal Server Error Pin
Jason Witty2-Mar-08 12:06
Jason Witty2-Mar-08 12:06 
GeneralZip Codes on Linux Pin
sljtea12-Mar-06 13:01
sljtea12-Mar-06 13:01 
NewsMy JavaScript SOAP Client Pin
m.casati7-Nov-05 23:17
m.casati7-Nov-05 23:17 
GeneralMake This Work With ASP Form Pin
Wayne W11-Aug-05 3:56
Wayne W11-Aug-05 3:56 
GeneralRe: Make This Work With ASP Form Pin
Jason Witty11-Aug-05 6:11
Jason Witty11-Aug-05 6:11 
QuestionRe: Make This Work With ASP Form Pin
Tim Whitley25-Feb-10 7:44
professionalTim Whitley25-Feb-10 7:44 
AnswerRe: Make This Work With ASP Form Pin
Jason Witty25-Feb-10 7:55
Jason Witty25-Feb-10 7:55 
GeneralNice Article Pin
Adam Tibi10-Aug-05 21:04
professionalAdam Tibi10-Aug-05 21:04 
GeneralRe: Nice Article Pin
Jason Witty11-Aug-05 6:12
Jason Witty11-Aug-05 6:12 
GeneralData Source Pin
RLyda10-Aug-05 5:03
RLyda10-Aug-05 5:03 
GeneralRe: Data Source Pin
Jason Witty10-Aug-05 20:10
Jason Witty10-Aug-05 20:10 
GeneralRe: Data Source Pin
RLyda11-Aug-05 4:16
RLyda11-Aug-05 4:16 
GeneralYou'll also need to enable some settings Pin
Troye Stonich5-Aug-05 7:23
Troye Stonich5-Aug-05 7:23 
GeneralRe: You'll also need to enable some settings Pin
Jason Witty5-Aug-05 7:31
Jason Witty5-Aug-05 7:31 
JokeRe: You'll also need to enable some settings Pin
that1guy.h16-Feb-06 12:49
that1guy.h16-Feb-06 12:49 
GeneralWorks with zip + 4 Pin
Jerry Walter5-Aug-05 4:47
Jerry Walter5-Aug-05 4:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.