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

Tutorial on Ajax

, 2 Oct 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
Simple Ajax example with C#, JavaScript and SQL Server

Introduction

Since Ajax has become extremely popular in Web applications, I have decided to write this simple application using C#, ASP.NET, JavaScript and Microsoft SQL 2005. I hope that this code will help junior developers to be able to incorporate Ajax in their application. The whole application can be downloaded and used ---- I have also included the SQL Script ---- that only requires data population.

Background

In this application, a user can select one of the makes of a car from a dropdownlist --- and populate the adjacent dropdownlist with that particular car's models with Ajax.

The application takes the value of the "make" dropdownlist and gets connected to the server asynchronously with JavaScript. The server returns the model of the particular cars as formatted string avoiding traditional refresh. Some of the code snippets are included in the article. However, to play with the code, you have to download and extract the zip file and simply run the script provided and finally add some data such as Make and Model to the corresponding table.

Using the Code

To use the code, download the entire contents of the zip file, run the script in your database, populate "Make" and "Model" tables with some data on it, and simply run the application. I have not included all the instructions to run the code in Visual Studio 2005. A slightly experienced user would automatically find out the way. This code runs perfectly fine with Internet Explorer. I have not tested the application with FIREFOX.

GO
/****** Object:  Table [dbo].[Make]  Script Date: 10/02/2007 16:21:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Make](
[CarMakeId] [int] IDENTITY(100,1) NOT NULL,
[CarMake] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[CarMakeDescription][varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_Make] PRIMARY KEY CLUSTERED 
(
    [CarMakeId] ASC

This is the code that retrieves the data from the database and sends the formatted string whenever it is requested.

public partial class AjaxData : System.Web.UI.Page
{
    private string _sqlCommand = 
        "select CarModelId, Model FROM model where carMakeId = {0}";
    protected void Page_Load(object sender, EventArgs e)
    {        
            string queryData = Request.QueryString["data"];
            if (string.IsNullOrEmpty(queryData)) return;
            int data = int.Parse(queryData);
            StringBuilder builder = new StringBuilder();
            using (SqlDataReader reader = 
                SqlHelper.GetDataReader(string.Format(_sqlCommand, data)))
            {
                while (reader.Read())
                {
                    builder.Append(reader[0] + ":" + reader[1]);
                    builder.Append("|");
                }

                builder.Remove(builder.Length - 1, 1);
            }
            Response.Write(builder.ToString());
            Response.End();
    }
}

Here is the JavaScript code that connects to the server:

<script language="javascript" type="text/javascript">
    
     var XmlHttp = null;

    function Display()
    {
       var serverData = "";
       CreateXmlHttp();
       
       if(XmlHttp != null)
       {     
            var ddlMakeList = document.getElementById(
                '<% = ddlMake.ClientID %>');
            var ddlModel = document.getElementById(
                '<% = ddlModel.ClientID %>');
            if(
                ddlMakeList.options[
                ddlMakeList.options.selectedIndex].value > 0)
            {               
                    ddlModel.disabled = false;
                    var requestUrl = 
                        "AjaxData.aspx?data=" + 
                        ddlMakeList.options[
                        ddlMakeList.options.selectedIndex].value;
                    XmlHttp.onreadystatechange = function ()
                    {
                        if(XmlHttp.readyState == 4 && XmlHttp.status == 200)
                        {
                           PopulateModel(XmlHttp.responseText, ddlModel);
                        }                       
                    };
                    
                    XmlHttp.open("GET", requestUrl, true);    
                     XmlHttp.send(null); 
            }
            else
            {            
                ddlModel.disabled = true;
            }            
        }       
    }    
    
    function PopulateModel(serverData, ddlModel)
    {
       var DataArray = serverData.split("|");
       var model = "";
       ddlModel.innerText = "";
       for(var i = 0; i < DataArray.length; i++)
       {
            var option  = document.createElement("OPTION");
            ddlModel.options.add(option);
            option.innerText = DataArray[i].split(":")[1];
            option.vaue = DataArray[i].split(":")[0];
       }
    } 
    
    function CreateXmlHttp()
    {    
    try    
        {        
            XmlHttp = new ActiveXObject("Msxml2.XmlHttp");    
        }    
        catch(e)    
        {        
            try        
            {            
            XmlHttp = new ActiveXObject("Microsoft.XmlHttp");        
            }         
            catch(oc)        
            {            
            XmlHttp = null;        
            }    
         }
         if(!XmlHttp && typeof XmlHttpRequest != "undefined")     
         {        
         XmlHttp = new XmlHttpRequest();    
         }
         
    }    </script>

Here is the code snippet for the server controls:

<div> 
    <asp:DropDownList ID="ddlMake" runat="server" onchange="Display()"> 
    </asp:DropDownList>    
    <asp:DropDownList id="ddlModel" runat="server" Enabled="false">
    </asp:DropDownList> </div> 

Any feedback, suggestions or comments are appreciated.

History

  • 2nd October, 2007: Initial post

License

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

Share

About the Author

Shiva Adhikari

United States United States
I am Software Enginner currently working in Software company developing Web Application using ASP.NET, C#, SQl, JavaScript, Ajax and JSON

Comments and Discussions

 
QuestionIncorporate AJAX in C# Pinmemberlisad_tgc15-Nov-07 5:54 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 2 Oct 2007
Article Copyright 2007 by Shiva Adhikari
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid