Click here to Skip to main content
15,860,859 members
Articles / Web Development / HTML
Article

Dropdown Box Using AJAX

Rate me:
Please Sign up or sign in to vote.
4.38/5 (127 votes)
22 Jan 2007CPOL4 min read 1.3M   854   119   49
This article illustrates two dropdown-boxes with nations and states. When selecting a particular nation, the corresponding states will be in the states dropdownbox.

What is AJAX?

AJAX, an acronym for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page's interactivity, speed, and usability.

Using the XmlHttp Object

An XmlHttp object can be created like this:

JavaScript
<script language="javascript">
  //Global XMLHTTP Request object
var XmlHttp;

//Creating and setting the instance of appropriate XMLHTTP Request object to 
//a "XmlHttp" variable  
function CreateXmlHttp()
{
 //Creating object of XMLHTTP in IE
 try
 {
  XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 }
 catch(e)
 {
  try
  {
   XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch(oc)
  {
   XmlHttp = null;
  }
 }
 //Creating object of XMLHTTP in Mozilla and Safari 
 if(!XmlHttp && typeof XMLHttpRequest != "undefined") 
 {
  XmlHttp = new XMLHttpRequest();
 }
}
</script>

Send the request to the server side page

We can send a request to the server page to retrieve the data from the server through the XmlHttp object.

JavaScript
var requestUrl = "WebForm2.aspx" + "?SelectedCountry=" + (selectedCountry);
 CreateXmlHttp();
 
 // If browser supports XMLHTTPRequest object
 if(XmlHttp)
 {
  //Setting the event handler for the response
  XmlHttp.onreadystatechange = HandleResponse;
  
  //Initializes the request object with GET (METHOD of posting), 
  //Request URL and sets the request as asynchronous.
  XmlHttp.open("GET", requestUrl,  true);
  
  //Sends the request to server
  XmlHttp.send(null);  
 }

The above code explains how to send a request to webpage2.aspx with the request object collection. This collection contains the selected country itself.

Process the client request

When the request is recieved on the server side, the server page executes the code and gives the response through the XmlHttp object:

VB
Dim xList As XmlNodeList
Dim xNode As XmlNode
Dim Str As String
xmlDoc.Load(Server.MapPath("CountriesAndStates.xml"))

Dim Country As String = Request.QueryString("SelectedCountry")
Dim query As String = ("/countries/country[@name='" & country & "']")
xlist = xmlDoc.SelectNodes(query)

Response.Clear()
 
For Each xNode In xList
     If xNode.HasChildNodes = True Then
          For Each xN As XmlNode In xNode.ChildNodes
               Str &= xN.InnerText & "-"
          Next
     End If
Next

Response.Clear()
Response.ContentType = "text/xml"
Response.Write(str)
Response.End()

Using the XmlHttp object to retrieve the data

Recieving the response from the server page can be done like this:

The valid list of XMLHttpRequest ready states is listed in the following table:

Value

Description

0

Uninitialized

1

Loading

2

Loaded

3

Interactive

4

Complete

The list of status codes for the HTTP status is given below:

1xx Informational

Request received, continuing process.

  • 100: Continue
  • 101: Switching Protocols

2xx Success

The action was successfully received, understood, and accepted.

  • 200: OK
  • 201: Created
  • 202: Accepted
  • 203: Non-Authoritative Information
  • 204: No Content
  • 205: Reset Content
  • 206: Partial Content
  • 207: Multi-Status

3xx Redirection

The client must take additional action to complete the request.

  • 300: Multiple Choices
  • 301: Moved Permanently. This and all future requests should be directed to another URI.
  • 302: Found this the most popular redirect code, but also an example of industrial practice contradicting the standard. HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was "Moved Temporarily"), but popular browsers implemented it as a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to disambiguate between the two behaviors. However, majority of web applications and frameworks still use the 302 status code as if it were the 303.
  • 303: See Other (since HTTP/1.1). The response to the request can be found under another URI using a GET method.
  • 304: Not Modified
  • 305: Use Proxy (since HTTP/1.1). Many HTTP clients (such as Mozilla and Internet Explorer) don't correctly handle responses with this status code.
  • 306 is no longer used, but reserved. Was used for 'Switch Proxy'.
  • 307: Temporary Redirect (since HTTP/1.1). In this occasion, the request should be repeated with another URI, but future requests can still be directed to the original URI. In contrast to 303, the original POST request must be repeated with another POST request.

4xx Client Error

The request contains bad syntax or cannot be fulfilled.

  • 400: Bad Request
  • 401: Unauthorized. Similar to 403/Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided. See basic authentication scheme and digest access authentication.
  • 402: Payment Required. The original intention was that this code might be used as part of some form of digital cash/micropayment scheme, but that has not happened, and this code has never been used.
  • 403: Forbidden
  • 404: Not Found
  • 405: Method Not Allowed
  • 406: Not Acceptable
  • 407: Proxy Authentication Required
  • 408: Request Timeout
  • 409: Conflict
  • 410: Gone
  • 411: Length Required
  • 412: Precondition Failed
  • 413: Request Entity Too Large
  • 414: Request-URI Too Long
  • 415: Unsupported Media Type
  • 416: Requested Range Not Satisfiable
  • 417: Expectation Failed
  • 449: Retry With A Microsoft extension: The request should be retried after doing the appropriate action.

5xx Server Error

The server failed to fulfill an apparently valid request.

  • 500: Internal Server Error
  • 501: Not Implemented
  • 502: Bad Gateway
  • 503: Service Unavailable
  • 504: Gateway Timeout
  • 505: HTTP Version Not Supported
  • 509: Bandwidth Limit Exceeded. This status code, while used by many servers, is not an official HTTP status code.
JavaScript
if(XmlHttp.readyState == 4)
 {
  // To make sure valid response is received from the server, 
  // 200 means response received is OK
  if(XmlHttp.status == 200)
  {  
   ClearAndSetStateListItems(XmlHttp.responseText);
  }
  else
  {
   alert("There was a problem retrieving data from the server." );
  }
 }

There are two types of XmlHttp responses for rectrieving the response.

  1. responseText
  2. responseXML

Show the states in the dropdownbox

The responseText is split using the split function and the response is assigned to an array.

Then, the array values are added in the dropdown list.

JavaScript
var stateList = document.getElementById("stateList");
 //Clears the state combo box contents.
 for (var count = stateList.options.length-1; count >-1; count--)
 {
  stateList.options[count] = null;
 }

 var stateNodes = countryNode.split("-");
 //window.alert(stateNodes) 
 var textValue; 
 var optionItem;
 //Add new states list to the state combo box.
 for (var count = 0; count < stateNodes.length; count++)
 {
     textValue = (stateNodes[count]);
  optionItem = new Option( textValue, textValue,  false, false);
  //window.alert(textValue); 
  //stateList.appendChild(textValue); 
  stateList.options[stateList.length] = optionItem;
 }

This is my first article in The Code Project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
have been working in web technologies for the last 8 years.

Comments and Discussions

 
Generalwhile adding maste rpage its not working Pin
emmy 190026-Jul-09 3:23
emmy 190026-Jul-09 3:23 
GeneralRe: while adding maste rpage its not working Pin
sathesh pandian26-Jul-09 23:00
sathesh pandian26-Jul-09 23:00 
GeneralRe: while adding maste rpage its not working Pin
sathesh pandian26-Jul-09 23:07
sathesh pandian26-Jul-09 23:07 
GeneralIs there any possible ajax livevalidation for textbox ,combo box in asp.net visual studio 2005... Pin
sathiyarajg17-Jun-09 19:24
sathiyarajg17-Jun-09 19:24 
GeneralRe: Is there any possible ajax livevalidation for textbox ,combo box in asp.net visual studio 2005... Pin
sathesh pandian17-Jun-09 20:23
sathesh pandian17-Jun-09 20:23 
GeneralSome Assistance Required. Urgently. Pin
ramnamsatya22-Apr-09 12:07
ramnamsatya22-Apr-09 12:07 
Generalhi Pin
balajivarnan4-Feb-09 1:44
balajivarnan4-Feb-09 1:44 
GeneralRe: hi Pin
sathesh pandian4-Feb-09 22:27
sathesh pandian4-Feb-09 22:27 
GeneralRe: hi Pin
balajivarnan8-Feb-09 19:18
balajivarnan8-Feb-09 19:18 
Generalonchange event not fired in Chrome Pin
balajivarnan9-Feb-09 2:17
balajivarnan9-Feb-09 2:17 
GeneralRe: onchange event not fired in Chrome Pin
sathesh pandian9-Feb-09 22:54
sathesh pandian9-Feb-09 22:54 
QuestionCan be improved Pin
GilesHinton28-May-08 0:45
GilesHinton28-May-08 0:45 
AnswerRe: Can be improved Pin
sathesh pandian23-Jul-08 21:01
sathesh pandian23-Jul-08 21:01 
QuestionRE Pin
Swapnil Salunke19-May-08 23:57
Swapnil Salunke19-May-08 23:57 
AnswerRe: RE Pin
Swapnil Salunke20-May-08 0:27
Swapnil Salunke20-May-08 0:27 
AnswerRe: RE Pin
sathesh pandian20-May-08 1:02
sathesh pandian20-May-08 1:02 
GeneralHi Pin
mkumar22-Feb-08 4:01
mkumar22-Feb-08 4:01 
GeneralRe: Hi Pin
sathesh pandian21-Apr-08 21:03
sathesh pandian21-Apr-08 21:03 
GeneralMasterPage cs file is missing Pin
madhan_genn14-Feb-08 2:43
madhan_genn14-Feb-08 2:43 
GeneralRe: MasterPage cs file is missing Pin
sathesh pandian21-Apr-08 22:14
sathesh pandian21-Apr-08 22:14 
Hi,

just forget about the master page in tht zip file.

It won't need to run the application.

If it gives errors, Just remove that file from the solution.

All The Best

Sathesh Pandian

Questionrequest problem Pin
J51219825-Sep-07 3:22
J51219825-Sep-07 3:22 
AnswerRe: request problem Pin
sathesh pandian8-Sep-07 0:18
sathesh pandian8-Sep-07 0:18 
GeneralRe: request problem Pin
sathesh pandian21-Apr-08 20:49
sathesh pandian21-Apr-08 20:49 
Generalsource code problems Pin
Parthasarathy Mandayam4-Sep-07 7:40
Parthasarathy Mandayam4-Sep-07 7:40 
GeneralRe: source code problems Pin
sathesh pandian8-Sep-07 0:19
sathesh pandian8-Sep-07 0:19 

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.