You are on page 1of 16

AJAX for Beginners (Part 2) - Using

XMLHttpRequest and jQuery AJAX to


implement a cascading dropdown
Rahul Rajat Singh, 14 Jan 2013

Introduction
This article discusses the ways ASP.NET applications can implement asynchronous functionality, i.e.,
AJAX by using XMLHttpRequest object and jQuery AJAX.

Background
In Part 1 of this series we have seen various ways an ASP.NET developer can implement the AJAX
functionality in the web applications. We have also seen how to use the ASP.NET AJAX server
controls. Now the focus of this article will be on using XMLHttpReuqest object and jQuery AJAX to
implement the asynchronous behavior in the web applications.

XMLHttpObject facilitates the exchange of data between client and server behind the scenes i.e. the
partial page update is possible using the XMLHttpObject.

jQuery is a JavaScript framework which makes a lot of client side work easy for the developers.
jQuery AJAX is a set of routines that provides behind the scenes communication between client and
server thus facilitating partial page updates.

Using the code


In this article we will try to work on a very common problem faced by many developers. We will try
to implement the cascading dropdown lists using AJAX. We will implement this first using
the XMLHttpObject and then by jQuery AJAX.

Before starting with the problem at hand let us understand the solution and the desired functionality.
Let us say we have a database keeping a list of all the continents and countries. The user will be
presented with two drop down lists. First dropdown will contain a list of continents and when user
select any continent from this list the second dropdown list should be updated asynchronously i.e.
without causing any postback.
Let us look at the Database table containing the list of continents and countries and the containing
data.
Note: The database has not been optimized or normalized in any way because that was not the
focus of this article.

Now we have a helper class that takes care of all the database communications. This class ideally
should be present as a separate solution for Data Access layer but for the sake of simplicity I have
created this class.

Hide Shrink Copy Code


public class DBHelper
{
public static DataTable GetContinentList()
{
DataTable result = null;

try
{
using (SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select distinct continentName from Countries";

using (SqlDataAdapter da = new SqlDataAdapter(cmd))


{
result = new DataTable();
da.Fill(result);
}
}
}
}
catch (Exception)
{
//Pokemon exception handling
}
return result;
}

public static DataTable GetCountriesList(string continentNmame)


{
DataTable result = null;

try
{
using (SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select countryName from Countries where continentName =
@continent";
cmd.Parameters.Add(new SqlParameter("@continent", continentNmame));

using (SqlDataAdapter da = new SqlDataAdapter(cmd))


{
result = new DataTable();
da.Fill(result);
}
}
}
}
catch (Exception)
{
//Pokemon exception handling
}
return result;
}
}

This class is will help in retrieving the list of continents and list of countries specific to that continent.
Let us now start working on the real problem.

Using XMLHttpObject

Let us create a page with two drop down lists (default.aspx). We will initialize the first drop down list
with first continent name and second dropdown list with the countries of that continent. We will then
use XMLHttpObjectto change the contents of second dropdown list based on user selection of first
dropdown. The code behind of this page will contain the logic for page_load only.

Hide Copy Code


protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//Let us populate the list of continents in the first drop down
drpContinent.DataSource = DBHelper.GetContinentList();
drpContinent.DataTextField = "continentName";
drpContinent.DataValueField = "continentName";
drpContinent.DataBind();

//Set the second dropdown as the list of all countries of selected continent
drpCountry.DataSource = DBHelper.GetCountriesList(drpContinent.SelectedValue);
drpCountry.DataTextField = "countryName";
drpCountry.DataValueField = "countryName";
drpCountry.DataBind();
}
}

Now next thing we want to do is to handle the onchange event of the first dropdown on client side.

Hide Copy Code


<asp:DropDownList ID="drpContinent" runat="server" onchange="UpdateCountries();">
</asp:DropDownList>

Now to use XMLHttpObject to get the list of countries based on user selection, we need to do the
following:

1. Create the XmlHttpObject.


2. Retrieve the current user selection of first dropdown
3. Pass this value to a web page on server as query string using XMLHttpObject.
4. Handle the response of this async request we just made.
5. Retrieve the values in the response.
6. Change the second dropdown lists items as per the new values found in response.

The important thing to note in the above algorithm is that we need a page that can handle this
asynchronous request, extract the query string and then push the results to the response. Let us
create a page called frmForAjaxCalls.aspx for this purpose and implement the functionality.

Hide Copy Code


public partial class frmForAjaxCalls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string continentName = Request.QueryString["cont"] as string;

if (continentName != null)
{
DataTable table = DBHelper.GetCountriesList(continentName.Trim());

string result = string.Empty;

foreach (DataRow r in table.Rows)


{
result += r["countryName"].ToString() + ";";
}

Response.Clear();
Response.Write(result);
Response.End();
}
}
}

Now the only thing remaining is the client side JavaScript code that will call this page
using XMLHttpObject. Following code will show how it is done.

Hide Shrink Copy Code


var xmlHttp;

function UpdateCountries()
{
//Let us create the XML http object
xmlHttp = null;

if(window.XMLHttpRequest)
{
//for new browsers
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
//for old ones
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}

if(xmlHttp != null)
{
//eveyhthing so far is just fine, lets proceed

//Retreive the value of the first drop down list


var contName = document.getElementById('<%=drpContinent.ClientID %>').value;

//Handle the response of this async request we just made(subscribe to callback)


xmlHttp.onreadystatechange=state_Change;

//Pass the value to a web page on server as query string using XMLHttpObject.
xmlHttp.open("GET","frmForAjaxCalls.aspx?cont="+contName,true);
xmlHttp.send(null);
}
}

//Handle the response of this async request


function state_Change()
{
if (xmlHttp.readyState==4)
{
// 4 = "loaded"
if (xmlHttp.status==200)
{
//request was successful. so Retrieve the values in the response.
var countries = xmlHttp.responseText.split(';');
var length = countries.length;

//Change the second dropdownlists items as per the new values foudn in response.
//let us remove existing items
document.getElementById('<%=drpCountry.ClientID %>').options.length = 0;

//Now add the new items to the dropdown.


var dropDown = document.getElementById('<%=drpCountry.ClientID %>');
for(var i = 0; i < length - 1; ++i)
{
var option = document.createElement("option");
option.text = countries[i];
option.value = countries[i];

dropDown.options.add(option);
}
}
}
}

Now when we run this page we can see that the selection on first dropdown list will trigger the async
communication with the server and the second dropdown list will be populated with the values of
countries in that continent. All this was done without having any postback to the server.

Using jQuery AJAX

Let us create a similar page with two drop down lists (default2.aspx). We will initialize the first drop
down list with first continent name and second dropdown list with the countries of that continent.
We will then use jQuery AJAX to change the contents of second dropdown list based on user
selection of first dropdown. The code behind of this page will contain the logic for page_load.

Hide Copy Code


protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//Let us populate the list of continents in the first drop down
drpContinent.DataSource = DBHelper.GetContinentList();
drpContinent.DataTextField = "continentName";
drpContinent.DataValueField = "continentName";
drpContinent.DataBind();

//Set the second dropdown as the list of all countries of selected continent
drpCountry.DataSource = DBHelper.GetCountriesList(drpContinent.SelectedValue);
drpCountry.DataTextField = "countryName";
drpCountry.DataValueField = "countryName";
drpCountry.DataBind();
}
}
Now unlike XMLHttpObject, if we are using jQuery we don't have to create another page to
handle the async request. What we can do is to have a static function in the asme page (or we could
create a separate page if we want to) that will take some arguments and return some value. Passing
the argument to this function, invoking this function and and handling the result will be the jQuery's
responsibility on client side. Let us look at this function:

Hide Copy Code


[System.Web.Services.WebMethod]
public static string OnContinentChange(string continentName)
{
DataTable table = DBHelper.GetCountriesList(continentName.Trim());

string result = string.Empty;

foreach (DataRow r in table.Rows)


{
result += r["countryName"].ToString() + ";";
}

return result;
}

This static function should also be decorated with an attribute WebMethod. This indicates that this
method will be called from client side.

Note: This static method with WebMethod attribute can be thought of as the small web service that
can be accessed from client side using this page's URL.

Now to use jQuery AJAX to get the list of countries based on user selection we need to do the
following:

1. Handle the onchange event of the first dropdown.


2. Retrieve the current user selection of first dropdown
3. Create a JSON object for passing this data to the server.
4. Specify the page/method name to be called.
5. Handle the response callback.
6. Retrieve the values in the response.
7. Change the second dropdownlists items as per the new values found in response.

Following code will shows how it is done using jQuery:

Hide Shrink Copy Code


$(document).ready(function() {
//Handle the change event for the drop down list
$("#drpContinent").change(function() {
//create the ajax request
$.ajax( {
type: "POST", //HTTP method
url: "Default2.aspx/OnContinentChange", //page/method name
data: "{'continentName':'"+$('#drpContinent').val() +"'}", //json to represent
argument
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) { //handle the callback to handle response
//request was successful. so Retrieve the values in the response.
var countries = msg.split(';');
var length = countries.length;

//Change the second dropdownlists items as per the new values foudn in response.
//let us remove existing items
document.getElementById('<%=drpCountry.ClientID %>').options.length = 0;

//Now add the new items to the dropdown.


var dropDown = document.getElementById('<%=drpCountry.ClientID %>');
for(var i = 0; i < length - 1; ++i) {
var option = document.createElement("option");
option.text = countries[i];
option.value = countries[i];

dropDown.options.add(option);
}
}
});
});
});

Now when we run this page we can see that the selection on first dropdown list will trigger the async
communication with the server and the second dropdown list will be populated with the values of
countries in that continent. All this was done without having any postback to the server.

Points of Interest
We have seen two ways we can implement AJAX behavior in an ASP.NET website. First method was
using XMLHttpObject and second one is using the jQuery AJAX. We have had only a cursory look at
these two ways to understand how things can be done. There are lot of options related to both these
approaches that can be customized to have better control over the asynchronous communication. I
suggest we reading about these two approaches in details will really help in better understanding to
things.

We also solved a very common problem that developers (new) face and that is creating cascading
dropdown lists. This article presents 2 ways of doing that. We can also use AJAX controls toolkit to
achieve this and many more AJAX functionalities. But perhaps that deserves a separate discussion.

Background
Desktop applications and web applications have one major difference and that is the stateless nature
of web applications. A website runs on a client and communicates with a server in a stateless
manner. So every action taken by the user on his browser has to be propagated back to the web
server to determine the outcome of that action. Due to this required postback to the server, web
applications find it very difficult to achieve a high degree of responsiveness in terms of user interface
and functionality (something that desktop applications manage quite easily).

AJAX, i.e., Asynchronous JavaScript and XML, is the technique that can be used to have
communication between the client and server without needing a postback. The benefit of avoiding
postback is faster response to the user, the page in the browser is not changed/refreshed/posted so
the user can continue to use it while data is sent to the server and user actions like keypresses can
also be communicated to the server to provide more meaningful results (example: autosuggest), i.e.,
enhanced overall usability of the web application.

AJAX is a set of W3C complaint technologies that facilitate this asynchronous communication
between the client and server. As an ASP.NET developer, we can include AJAX in our web application
using:

 XMLHTTPRequest object in JavaScript - The W3C standard way of having AJAX functionality.
 Using jQuery AJAX - jQuery AJAX provides a wrapper using XMLHTTPRequest making the life of
developers a little easy.
 Using Microsoft AJAX library - This is a JavaScript framework that makes working with AJAX easy
for ASP.NET developers
 AJAX Control Toolkit - A set of controls that can be used with ASP.NET to incorporate AJAX
functionality.
 ASP.NET AJAX Server controls - These controls provide the basic building blocks to have AJAX
functionality on an ASP.NET page.

So as an ASP.NET developer why should one learn to use AJAX? For the simplest of reason that AJAX
will increate the overall usability of the website. Major benefits of incorporating AJAX functionality in
a website include:

 Partial page updates - Only the portion of the page that needs updating is posted back and not the
whole page.
 Faster user response - Since only a subset of data moves between the client and server, the results
are shown quickly.
 Enhanced user interface - With AJAX, desktop like user interface with progress indicators and
timers can be implemented.
 Enhanced features - with AJAX features like autocomplete can be implemented.

This article mainly focuses on ASP.NET AJAX Server controls. Other techniques for implementing
AJAX deserves a separate article each (which I will post in due time) but for now, our focus will be
ASP.NET AJAX server controls.

Using the code


ASP.NET AJAX server controls mainly provide functionality for having partial page updates, update
progress indication, and frequent updates based on a timer. Also, it takes care of generating all the
JavaScript that is required to perform these functionalities. So with these controls, the developer
doesn't have to write any JavaScript to implement AJAX.

The controls provided by ASP.NET for having AJAX functionality are:

1. ScriptManager
2. ScriptManagerProxy
3. UpdatePanel
4. UpdateProgress
5. Timer

Let us try to understand these controls one by one and try to work out an example to see how each
of them can be used to implement AJAX features.

ScriptManager

The ScriptManager control is a non visual component on the page. This control is required on each
page that needs to have AJAX features implemented on it. The main functionality of
a ScriptManager control is to push Microsoft AJAX framework code to the client side when the
page is being rendered. This control can be thought of as the agent which will write the JavaScript
required on the client side to facilitate AJAX functionality.

There should be only one ScriptManager control on the page that needs AJAX functionality. Let us
create a webpage and add a ScriptManager control to it:

Hide Copy Code


<asp:ScriptManager ID="ScriptManager1" runat="server" />

ScriptManagerProxy

We have seen that the ScriptManager control is required on the page that needs AJAX
functionality. We also know that there should be only one ScriptManager control on the page.
Now consider a situation where there is a master page and content page and both need AJAX
functionalities. There is one more scenario, let's say we have a UserControl that needs AJAX and it
has to be added on a page where AJAX is already implemented. Since there could be only
one ScriptManager on the page, adding a ScriptManager control in these scenarios will result in
two ScriptManager controls on the page. So to handle such conditions,
theScriptManagerProxy control can be used.

ScriptManagerProxy should be used on content pages that have master pages containing
a ScriptManagercontrol. It can also be used inside UserControls when the page containing the
UserControl already has the ScriptManager control.
UpdatePanel

This is a container control that contains other ASP.NET controls. This control defines a region that is
capable of making partial page updates. We can add various server controls inside
an UpdatePanel and this controls inside the UpdatePanel will communicate to the server
irrespective of the page's postback.

Let us add an UpdatePanel on the page and some server controls inside it. We will try to do some
arithmetic operations inside this UpdatePanel and try to get the results without a postback. Once
the controls are added, the design view of the page will look like:

Now let us handle the button click event and perform the arithmetic operations on that:

Hide Copy Code


protected void btnCalculate_Click(object sender, EventArgs e)
{
try
{
int a = Convert.ToInt32(txtA.Text);
int b = Convert.ToInt32(txtB.Text);

int sum = a + b;
int difference = a - b;
int multiplication = a * b;
Label1.Text = string.Format("Sum = {0}", sum);
Label2.Text = string.Format("Difference = {0}", difference);
Label3.Text = string.Format("Multiplication = {0}", multiplication);
}
catch (Exception ex)
{
//pokemon exception handling
}
}

Now since all the controls are inside the UpdatePanel control, clicking the button will not result in a
postback but it will asynchronously call the server-side function and give us the results. When we run
the page in the browser:

Notice that clicking on the button does not cause the postback but gives us the result
asynchronously. We can control partial page updates using the UpdateMode property of
the UpdatePanel and setting Trigger.

UpdateProgress

The scenario we just handled gave us the results instantly, but imagine a scenario where the server
side processing for the asynchronous event takes some time. If the operation is time consuming then
we can provide the user feedback by using the UpdateProgress control inside the UpdatePanel.
Let us have one more UpdatePanel on the page doing the same task, but this time we will make the
server side functionality take more time than required (by using sleep). We will add a
simple UpdateProgress control to make the user aware of the fact that some processing is being
done by the page right now. Let us look at the Design view of
this UpdatePanel and UpdateProgress control now.

Let us handle the server side event for button click but this time let's add a sleep for some time here.

Hide Copy Code


protected void btnCalculate2_Click(object sender, EventArgs e)
{
try
{
//Lets pretend that we are doiing something time consuming
System.Threading.Thread.Sleep(3000);
int a = Convert.ToInt32(txtA2.Text);
int b = Convert.ToInt32(txtB2.Text);

int sum = a + b;
int difference = a - b;
int multiplication = a * b;

Label4.Text = string.Format("Sum = {0}", sum);


Label5.Text = string.Format("Difference = {0}", difference);
Label6.Text = string.Format("Multiplication = {0}", multiplication);
}
catch (Exception ex)
{
//pokemon exception handling
}
}

Now when we run the page and click the button, the updateProgress message will be shown.

We can also have images and animated GIFs inside the updateProgress control to provide more
user friendly feedback.

Timer

There might be some scenarios where we want to update a particular portion of the page after some
time duration irrespective of user action. To achieve this, we can use the Timer control. Let us add a
timer control to our page and display the server time after every 5 seconds. The design view of the
page will look like:
Let us now handle the timer_tick event. Since the control is inside the UpdatePanel the time will
be updated after every 5 seconds without causing any postback. Let us look at the server side code
for the timer event and then run the page and see the time changing every 5 seconds.

Hide Copy Code


protected void Timer1_Tick(object sender, EventArgs e)
{
Label8.Text = DateTime.Now.ToString();
}

Points of interest
What we have tried to do in this article is understand what is AJAX and why it might be useful. There
are various ways of implementing AJAX in an ASP.NET application. We have only touched the very
basics of the ASP.NET AJAX server controls in this article. There are a lot of configuration options and
properties associated with each of these server controls which we have not discussed. Understanding
these controls gives us one way of having AJAX features in our website. I will perhaps discuss the
other ways of implementing AJAX in separate articles so that as an ASP.NET developer can learn all
he needs to know about AJAX and how to implemented it in a better way.

You might also like