Click here to Skip to main content
Click here to Skip to main content

Dropdown Box Using AJAX

By , 22 Jan 2007
 

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:

<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.

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:

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.
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.

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)

About the Author

sathesh pandian
Technical Lead
India India
have been working in web technologies for the last 8 years.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalwhile adding maste rpage its not workingmemberemmy 190026-Jul-09 3:23 
i need a solution with master page..
is it possible to add master page? while adding master page its not working why??
GeneralRe: while adding maste rpage its not workingmembersathesh_pandian26-Jul-09 23:00 
hi,
 
i have provided this raw ajax only before the introduction of master pages. But we can achieve the same through updatepanel also.
 
If you like to use the raw ajax, then please provide me your html code, so that i can able to give you the solution.
 
Please check the element's ids are correct because when you use master pages, the ids of content page elements will get changed. thats the only reason why its not working.
 
All The Best
 
Sathesh Pandian

GeneralRe: while adding maste rpage its not workingmembersathesh_pandian26-Jul-09 23:07 
The normal code to select the element using id is
 
document.getElementById('elementID');
 
This element is a html element.
 

The same will applicable if the element is even a server control but not a complex control.
 
complex controls are like datagrid, panel etc.
 
If you put any controls in it, the id of the control will change. For this, you have to use clientID.
 
document.getElementById('<%Element.ClientID');
 

This element should be a server control.
 
All The Best
 
Sathesh Pandian

GeneralIs there any possible ajax livevalidation for textbox ,combo box in asp.net visual studio 2005...membersathiyarajg17-Jun-09 19:24 
Hi,
 
I am new in asp.net ..
I want to know Is there any possible ajax livevalidation for textbox ,combo box in asp.net visual studio 2005...
ans should greatly appreciated!!...
GeneralRe: Is there any possible ajax livevalidation for textbox ,combo box in asp.net visual studio 2005...membersathesh_pandian17-Jun-09 20:23 
hi you can validate those controls by using validation controls but the functionality should be in a neat flow.
 
You don't need to use core ajax for this. You can use updatepanel and script manager in the visual studio toolbox if they are already placed in the toolbox.
 
Please refer
 
http://www.asp.net/ajax/[^]
 
All The Best
 
Sathesh Pandian

GeneralSome Assistance Required. Urgently.memberramnamsatya22-Apr-09 12:07 
Hello Sathesh! I found your example very informative. But there persists a problem. I virtually know nothing of VB and its directives and syntaxes. I am conversant in C#. It would greatly benefit, if you kindly provided me with the respective C# versions for the server side codings of the pages WebForm2.aspx.vb and WebForm1.aspx.vb from your application. There are several things that I am at a loss with. For eg. when trying out the eg, in C#, the compiler prompts errors for missing out on some directives/assemblies which would be required for using classes like XmlNodeList( the one used in your sample for declaring the variable xlist) etc.
Also there are some other things that I would like to consult with you. Eg. where does the parameter 'countryNode' come from for the method ClearandSetStateListItems(). There's more. In the code beside pages you have used the variable xmlDoc, but without declaring it anywhere beforehand. Please explain.
All in all, although the sample is quite good, I haven't been able to apply it to my full satisfaction. Kindly provide me with the corresponding C# encoded Version for this example ASAP. Mail ID---sw6boy@yahoo.co.in. Thank you.
Generalhimemberbalajivarnan4-Feb-09 1:44 
I am new to asp.net. i used ur sample..its working fine..when submit i am getting the city value is null..i want the city value to be inserted into db...Can u help me...
GeneralRe: himembersathesh_pandian4-Feb-09 22:27 
hi balajivarnan,
 
i have appreciated your efforts on trying my code.
 
While renderering the html code, the server will note down the viewstate and fix it in the page itself.
 
But when we are using the ajax, we don't change the viewstate informations. So the server won't get the changed values.
 
For this, You have to use some hidden values to retrive the selected city.
 
Add a function and this function should be called everytime when the selected city get changed.
 

<select id="stateList" style="Z-INDEX: 102; LEFT: 368px; POSITION: absolute; TOP: 128px" önchange="CityOnchange();"> </select><input id="selectedCity" type="hidden" runat="server" value="0" />
 

 
in the cityonchange funtion
 
you have to set the selected statevalue
 

var selectedCity=document.getElementsById('selectedCity');
 

var stateList= document.getElementById("stateList");
//Getting the selected state from state combo box.
var selectedState = stateList.options[stateList.selectedIndex].value;
 
selectedCity.value=selectedState;
 

 
This code will help you.
 
Please give proper and meaningful names to the elements.
 
All The Best
 
Sathesh Pandian

GeneralRe: himemberbalajivarnan8-Feb-09 19:18 
Thank you for your reply. I used hidden textbox to pass value.It's working fine...
 
I checked in IE and Mozilla your coding works fine...But in Google Chrome city is not get loaded...Is there any solution...
 
I have to check my code for all browsers..Please try to help me in this as soon as possible...
Generalonchange event not fired in Chromememberbalajivarnan9-Feb-09 2:17 
i found the solution..Instead of onchange i used onblur for state dropdown it's working fine in IE, mozilla and Chrome...
GeneralRe: onchange event not fired in Chromemembersathesh_pandian9-Feb-09 22:54 
good update.
 
All The Best
 
Sathesh Pandian

QuestionCan be improvedmemberGilesHinton28-May-08 0:45 
I'm afraid that there are several publically available libraries which exist which handle the sending and response of the XML more efficiently than the examples here.
 
Using try catch to work out which transport object is available in JS is a lazy and inefficient way of doing things - instead you can check if the object is null or its type is undefined - both of which are far more efficient than using error handling to achieve the same.
 
In addition, you should be aware that ASP.Net Ajax now uses JSON responses to retrieve its data - purely because it requires less bandwith; thus if you're sending back a BIG list of items, JSON is likely to be far more compressed than XML will be.
 
You also missed out other versions of the XML parser for IE which offer greater functionality for XSLT and XML DOM operations for browsers that support them.
 
Finally, the ASP.Net toolkit, although not the greatest piece of programming in the world due its over-coded nature and bugs does provide a mechanism not only to populate drop downs, but also cascading drop downs and is built in for free server-side.
 
I'd recommend that programmers who aren't that familiar with JavaScript (i.e. have only ever copied and pasted other peoples' code) should use this in preference to this solution.
AnswerRe: Can be improvedmembersathesh_pandian23-Jul-08 21:01 
Thanks for your comment. This article submitted 3 years before.At that time ,controltoolkits are not famous and familiar.
 
All The Best
 
Sathesh Pandian

QuestionREmemberSwapnil Salunke19-May-08 23:57 
Hello I am trying a sample application using AJAX as you have guided. I thought to add more like City List in the one which you made. But I am getting some errors in that The Following things I have tried.
 
1. Added cities in the xml file like
Maharashtra
Mumbai
Pune

And added one more function on statechanged But things are not workign for me.
If you can help me please
AnswerRe: REmemberSwapnil Salunke20-May-08 0:27 
Hello Smile | :)
 
I have done it But still if possible you post your view that would be much finer.
 
thanks & regards
Swapnil Smile | :)
AnswerRe: REmembersathesh_pandian20-May-08 1:02 
hi,
 
can you just briefly explain the code changes you have made and the errors?
then only i can understand what the problem is?
 
All The Best
 
Sathesh Pandian

GeneralHimembermkumar22-Feb-08 4:01 
Hi sathees,
 
I used ur sample. It is useful to me. i try to same sample in c# language. but it display some error is
 
'System.Web.HttpRequest.QueryString' is a 'property' but is used like a 'method'
 
error line - String country = Request.QueryString("SelectedCountry");
 
how to rectify this error.
 
reply to my mail mk10183@yahoo.co.in
 
Thanks.
 
by
 
kumar.
Rose | [Rose]
 
This allows you to set your preferences for the discussion boards.

GeneralRe: Himembersathesh_pandian21-Apr-08 21:03 
Hi,
 
you have tried to convert the vb file into C#.
 
String Country=Request.QueryString["SelectedCountry"]; is the correct code.
 
All The Best
 
Sathesh Pandian

GeneralMasterPage cs file is missingmembermadhan_genn14-Feb-08 2:43 
master page cs file is missing in the zip folder
 

Regards,
MadhanMohan Roll eyes | :rolleyes:
GeneralRe: MasterPage cs file is missingmembersathesh_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 problemmemberJ51219825-Sep-07 3:22 
when i access server for first time it retrieves the output from server.
 
when i access server for second time it does not retrieves the output from server it shows me the previous output
 
after deleting the cookie,off-line file,etc
 
it retrieves the output from server
 

why ????Cry | :((
 

thanks in advance for all ajax developer
 
JAYARAJ

AnswerRe: request problemmembersathesh_pandian8-Sep-07 0:18 
clear the cache.
 
it gives the output from cache.
 
use this
 
Response.Expires = 0;
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");
 
it will work.
 
All The Best
 
Sathesh Pandian

GeneralRe: request problemmembersathesh_pandian21-Apr-08 20:49 
Hi,
 
For this, check the dropdownbox is getting empty for every request and response.
 
All The Best
 
Sathesh Pandian

Generalsource code problemsmemberParthasarathy Mandayam4-Sep-07 7:40 
I downloaded the source code but it's missing several files.
 
Certified VB6, SQL 7 and ASP developer

GeneralRe: source code problemsmembersathesh_pandian8-Sep-07 0:19 
i have provided all the files what ever it needs in the zip file.
 
So try to download it again.
 
it will work.
 
All The Best
 
Sathesh Pandian

GeneralRe: source code problemsmembersathesh_pandian21-Apr-08 20:52 
Hi,
 
Don't worry about the missing files.
 
Just use the files as given in this zip file.
 
set the aspx page as the startup page.
 
All The Best
 
Sathesh Pandian

GeneralSend variables through POST methodmemberSurjit Madiwalar2-Sep-07 18:46 
Hi,
 
How do I achieve the same functionality using POST method.
How do we handle server side. Sample code(c#) would help.
 
Thanks & Regards,
Surjt
surjit.m@gmail.com
GeneralRe: Send variables through POST methodmembersathesh_pandian8-Sep-07 0:22 
you have to use the selectedindexchanged event for this.
 
refer this article
 
it will help you to understand.
 
http://msdn2.microsoft.com/en-us/library/0dzka5sf(vs.71).aspx[^]
 

 
All The Best
 
Sathesh Pandian

GeneralThank you very much!memberanhcomcom23-Aug-07 20:27 
That's a best lesson!
GeneralRe: Thank you very much!membersathesh_pandian24-Aug-07 6:49 
Thanks for your support.
 
All The Best
 
Sathesh Pandian

General3 Dropdown listsmemberrajska730-Jul-07 9:06 
Is there a way to make it into 3 dropdown lists?
 
The 1st DDL is for the world regions, the 2nd for countries and 3rd for states?
 
I tried expanding it with Ramaprasad Potturi's code, but it doesn't work.
 
Thanks.
 
Rajska
rajska7@gmail.com.
GeneralRe: 3 Dropdown listsmembersathesh_pandian6-Aug-07 6:21 
i have used one client side file and one server side file for the 2 dropdownbox.
 
You can do it with a single file.like the client side code is same and the server side code will be a different one.
 
you can try this with 3 dropdownboxes you can differentiate it with them by
 
the querystrings.
 
In the page load, you can differentiate them .
 
try it.

 
All The Best
 
Sathesh Pandian

GeneralRe: 3 Dropdown listsmemberrajska77-Aug-07 7:38 
So there will be two sets of XML lists?
 
One of regions and countries.
 
And another for countries and states?
 
Isn't that cumbersome?
GeneralRe: 3 Dropdown listsmembersathesh_pandian8-Aug-07 5:11 
exactly. yes it contains two xml files.
 
All The Best
 
Sathesh Pandian

QuestionRe: 3 Dropdown listsmemberrajska78-Aug-07 6:27 
OK thank you.
 
But how do you connect the two XML files?
 
How do you make the childnode of the first XML file become the parentnode of the second XML file?
 
Thanks for help.
AnswerRe: 3 Dropdown listsmembersathesh_pandian14-Aug-07 1:34 
There is no need for two files actually.
 
You can get them from the attributes.
 
All The Best
 
Sathesh Pandian

GeneralUsing Ajax ExtensionmemberBino B11-Jul-07 0:04 
Can u pls give me an idea of how to handle the same with Ajax Extensions ie ASP.Net Ajax.
 
Regards
Bino

GeneralRe: Using Ajax Extensionmembersathesh_pandian11-Jul-07 0:09 
dear bino,
 

Please make sure u have downloaded all dll and all the ajax asp.net controls are in the toolbox?
 
Then you can use the control tool kit to try it?
 
set this then ask ur question
 
All The Best
 
Sathesh Pandian

GeneralRe: Using Ajax ExtensionmemberBino B2-Aug-07 2:56 
everything is set but im getting error still..
 
Regards
Bino

GeneralRe: Using Ajax Extensionmembersathesh_pandian22-Apr-08 4:49 
hey just check the IIS.
 
and restart the system.
 
All The Best
 
Sathesh Pandian

GeneralRe: Using Ajax ExtensionmemberGilesHinton28-May-08 0:38 
The whole idea is that you wouldn't need to use the AJAX extensions.
TBH the AJAX extensions library is slow, inefficient and includes bugs - the toolkit is far worse. Avoid it like the plague.
GeneralGood Articlememberrajmohan838-Jul-07 22:12 
Hi,
This article gave me a basic Knoledge of AJAX.
GeneralRe: Good Articlemembersathesh_pandian10-Jul-07 18:47 
thanks for your feedback rajmohan.
 
i am very happy about your feedback.
 
vote me if you feel good about the articles.
 


 
All The Best
 
Sathesh Pandian

Generalgive some ideasmemberryfyfhf1-Jul-07 22:07 
give some ideas to learn ajax
 
sadsam

GeneralRe: give some ideasmembersathesh_pandian25-Jul-07 23:36 
read the online tutorials in www.ajax.asp.net
 
All The Best
 
Sathesh Pandian

GeneralA nice Startermembervijayalaya1-Jan-07 18:16 
hi,
 
The article has provided me an nice insight towards Ajax.
Nicely done.Keep it up..
GeneralRe: A nice Startermembersathesh_pandian1-Jan-07 18:26 
thanx vijay
 
Sathesh Pandian

GeneralRe: A nice Startermembervinay_ruchisoft@yahoo.com2-Jan-07 18:49 
hi
but on post back dropdown list does not retain its value.
How will we retain the value of dropdown on post back
 
hi

GeneralRe: A nice Startermembersathesh_pandian21-Jan-07 17:36 
hi vinay,
 
i didn't use the asp web controls for this application.
 
i have used the html control.
 
if you want to use the post back method then you must set the
autopostback= true in the properties of dropdown list.
 
that will make the page to call the events in the code behind page.
 
But then there is no need for XmlHttp object to retrieve the results to the
 
current page.Code behind page do the rest of the work.
 
Sathesh Pandian

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 22 Jan 2007
Article Copyright 2006 by sathesh pandian
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid