Click here to Skip to main content
15,884,629 members
Articles / Web Development / HTML
Article

AJAX in Action

Rate me:
Please Sign up or sign in to vote.
3.64/5 (11 votes)
28 Sep 20053 min read 122K   540   66   15
See AJAX in action.

Introduction

I love AJAX, it really cleans my dishes. Unfortunately, in this article we will not be talking about washing detergent. If you like you can visit Clean My Dishes for more details. In this article we will be talking about AJAX (Asynchronous JavaScript and XML). All you need to know right now is that AJAX allows you to make server side calls without doing a postback.

Downloading the AJAX.NET Library

First of all, you need to download the AJAX.NET library created by Michael Schwarz. Now that you have downloaded the library and made the reference to the DLL in your project, we can start some dirty stuff.

What are we going to do?

Okay, here is what we are going to do. We are going to make a dropdown list using <select> HTML tags. We will populate the dropdown list from the database. Now when we select any item from the dropdown list, it will fetch the result from the database and display it on the screen in a DataGrid. All of this will happen with no pstback.

I highly recommend that you first read the basic instructions of using the AJAX.NET Library which are given at the above URL, so that you will have the basic idea.

AJAX in Action

Our first task is that when the page is loaded the dropdown list is populated with data from the database. But before that let's initialize our AJAX library by making a call in the page_load event.

C#
private void Page_Load(object sender, System.EventArgs e)
{
  Ajax.Utility.RegisterTypeForAjax(typeof(UsingAjax));
}

In this article we will be using the Northwind database. First of all you need to make a server method so that you can get a DataSet and bind it to the dropdown list. Let's make that method:

C#
[Ajax.AjaxMethod]
public DataSet GetDropDownListData()
{
  string query = "SELECT CategoryID,CategoryName FROM Categories ";
  SqlConnection myConnection = new SqlConnection(GetConnectionString());
  SqlDataAdapter ad = new SqlDataAdapter(query,myConnection);
  DataSet ds = new DataSet();
  ad.Fill(ds,"Categories");
  return ds;
}

As you might have already noticed, this method is marked with the Ajax.AjaxMethod attribute. This means that this method is going to be called from the client side. Now let's see how we can access this method from the client side.

JavaScript
function FillDropDownList()
{
  UsingAjax.GetDropDownListData(FillDropDownList_CallBack);
}

function FillDropDownList_CallBack(response)
{
  var ds = response.value;
  var html = new Array();

  if(ds!= null && typeof(ds) == "object" && ds.Tables!= null)
  {
    for(var i=0;i<ds.Tables[0].Rows.length;i++)
    {
      html[html.length] = "<option value=" + 
                          ds.Tables[0].Rows[i].CategoryID + ">" 
                          + ds.Tables[0].Rows[i].CategoryName + 
                          "</option>";
    }
    document.getElementById("Display").innerHTML = 
        "<select id=\"sel\" onchange=\" ChangeListValue" + 
        "(this.options[this.selectedIndex].value); \">" + 
        html.join("") + "</select>";
  }
}

Let me first explain the FillDropDownList() method. UsingAjax is the name of the class which contains the GetDropDownListData method which we implemented a few moments ago. We call FillDropDownList_CallBack() which contains the actual code to populate the dropdown list.

Take a look at the line below:

JavaScript
document.getElementById("Display").innerHTML = 
                       "<select id=\"sel\" onchange=\"

You must be wondering what "Display" is. Display is no more than a SPAN tag. I have implemented it below:

HTML
<span id="Display"></span>

Now let's go and see how the ChangeListValue method is implemented since it is called when the selection in the dropdown changes.

JavaScript
function ChangeListValue(index)
{
  GetResult(index);
}

ChangeListValue() calls GetResult(index). Now let's go to GetResult(index).

JavaScript
function GetResult(categoryID)
{
  UsingAjax.GetProductsByID(categoryID,GetResult_CallBack);
}

function GetResult_CallBack(response)
{
  var ds = response.value;
  if(ds!=null && typeof(ds) == "object" && ds.Tables!=null)
  {
    var s = new Array();
    s[s.length] = "<table border = 1>";

    for(var i=0;i<ds.Tables[0].Rows.length;i++)
    {
        s[s.length] = "<tr>";
        s[s.length] = "<td>" + ds.Tables[0].Rows[i].ProductID + "</td>";
        s[s.length] = "<td>" + ds.Tables[0].Rows[i].ProductName + "</td>";
        s[s.length] = "<td>" + ds.Tables[0].Rows[i].QuantityPerUnit + "</td>";
        s[s.length] = "</tr>";
    }
    s[s.length] = "</table>";

    document.getElementById("Display1").innerHTML = s.join("");
  }
}

GetResults() method calls the server side method "GetProductsByID".

C#
[Ajax.AjaxMethod]
public DataSet GetProductsByID(int categoryID)
{
  string query = "SELECT * FROM Products WHERE CategoryID = @CategoryID ";
  SqlConnection myConnection = new SqlConnection(GetConnectionString());
  SqlCommand myCommand = new SqlCommand(query,myConnection);

  myCommand.Parameters.Add("@CategoryID",categoryID);
  SqlDataAdapter ad = new SqlDataAdapter(myCommand);
  DataSet ds = new DataSet();

  ad.Fill(ds);
  return ds;
}

So, there you go now. When you select an item from the dropdown, your DataGrid will pull up new results without having to refresh the page. In other words, there will be no postback.

You should also make a BindControls() method that will populate the controls when the page loads. Here is my implementation of the BindControls() method. Keep in mind that we have already implemented the FillDropDownList() method above.

JavaScript
function BindControls()
{
  FillDropDownList();
}

After making the BindControls method you just need to call it when the page loads.

HTML
<body onload="BindControls();">

You also need to add these settings in the web.config file:

XML
<configuration>
  <system.web>
    <httpHandlers>
      <add verb="POST,GET " path="ajax /*.ashx"
           type="Ajax.PageHandlerFactory, Ajax" /> 
    </httpHandlers>  
    ...
  <system.web>
</configuration>

For your convenience I have attached the zip file which contains all the files you need for this project. I hope you like the article, happy coding!

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
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
GeneralAjax.dll is not working [modified] Pin
Akeel Qureshi7-Oct-08 18:34
Akeel Qureshi7-Oct-08 18:34 
Generali am finding error in this line of code(plz help me ) Pin
manoj.singh18-Jun-08 19:46
manoj.singh18-Jun-08 19:46 
GeneralRe: i am finding error in this line of code(plz help me ) Pin
Shreepad Deshpande7-Sep-10 19:09
Shreepad Deshpande7-Sep-10 19:09 
Questionwhat about imagebuttons?!!! Pin
coolshad30-Aug-06 5:13
coolshad30-Aug-06 5:13 
GeneralHelp Pin
guocang18-Feb-06 7:00
guocang18-Feb-06 7:00 
GeneralRe: Help Pin
azamsharp18-Feb-06 7:13
azamsharp18-Feb-06 7:13 
GeneralRe: Help Pin
keyur soni10-May-08 0:13
keyur soni10-May-08 0:13 
GeneralThe code doesn't work Pin
Amphysvena14-Feb-06 17:15
Amphysvena14-Feb-06 17:15 
GeneralzumiPage for ASP.NET Pin
Amir L.21-Dec-05 13:13
Amir L.21-Dec-05 13:13 
Generalsel1 value Pin
tbaseflug12-Dec-05 11:19
tbaseflug12-Dec-05 11:19 
GeneralAjax and object binding Pin
Anonymous28-Sep-05 11:08
Anonymous28-Sep-05 11:08 
NewsRe: Ajax and object binding Pin
Sarat Pediredla28-Sep-05 11:41
Sarat Pediredla28-Sep-05 11:41 
GeneralRe: Ajax and object binding Pin
azamsharp28-Sep-05 13:52
azamsharp28-Sep-05 13:52 
GeneralRe: Ajax and object binding Pin
vbinfo28-Sep-05 22:43
vbinfo28-Sep-05 22:43 
Hi guys,
Thanks for your replies.Sorry for not explaining it properly.
What I am trying to achieve is

To fill 3 drop downs in a webPage (asp.net 2.0) avoiding postback and I have come cross Ajax.

In my framework i dont pass dataset around but object/entity objects

3 DropDowns
Country - City -Hotel

The Webpage will call the BizTier methods
GetCountryList (Returns a collection of Countries) (bindinglist (of t)
GetCityList (Returns a collection of Cities) (bindinglist (of t)
GetHotelList (Returns a collection of Hotels) (bindinglist (of t)


now how can use Ajax with collections rather than dataset.

Azamsharp
Does you link shows something like this?

Sarat
Can I do the above with your implementation?

Thanks guys I am in a learning process as I was always a desktop Developer .

Thanks A lot
vbinfo@devnet247.com
GeneralRe: Ajax and object binding Pin
Anonymous29-Sep-05 5:12
Anonymous29-Sep-05 5:12 

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.