Click here to Skip to main content
15,860,844 members
Articles / Web Development / ASP.NET
Article

Tutorial on Ajax

Rate me:
Please Sign up or sign in to vote.
2.71/5 (4 votes)
2 Oct 2007CPOL2 min read 23.4K   122   31   1
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.

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

C#
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:

JavaScript
<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:

ASP.NET
<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)


Written By
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# Pin
lisad_tgc15-Nov-07 4:54
lisad_tgc15-Nov-07 4:54 
I want to have the ability to independently refresh the the ad on the page using AJAX.
I have the most recent AJAX Extensions installed and have update my web.config...
See example code:
**************************

using System;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Collections;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Reflection;

namespace TEST
{

public class AdFalk : TESTControl
{

//Variables defined for TEST.AdFalk
// These are private and not properties
int intWidth = 0, intHeight = 0, intKID = 0, intBID = 0;
int intLocation = 0;
string strPageName = "";
string strDayName = "";
string strSelectKey = "";
string strAdSpotID = "";
int intAdSpotID = 0;
string strKeywords = "";
string strProfile = "", strSite = "test.mysite";

TESTPage objUniversal;
bool DebugStatus;
StringWriter Response;

protected override void Render(HtmlTextWriter output)
{
objUniversal = this.CurrentPage;
DebugStatus = objUniversal.DebugStatus;
this.GetDefaults();

Response = new StringWriter();
DisplayHtml();
output.Write(Response.ToString());

objUniversal = null;
Response = null;

}

public void DisplayHtml()
{

//Display Variables for Debugging
if (DebugStatus)
Response.Write("

-- Ads Begin --

");

if (Defaults["DClocation"] != null)
intLocation = System.Convert.ToInt32(Defaults["DClocation"]);

if (Defaults["DCwidth"] != null && Defaults["DCwidth"].ToString() != "")
intWidth = System.Convert.ToInt32(Defaults["DCwidth"]);

if (Defaults["DCheight"] != null && Defaults["DCheight"].ToString() != "")
intHeight = System.Convert.ToInt32(Defaults["DCheight"]);

if (Defaults["CampaignID"] != null && Defaults["CampaignID"].ToString() != "")
intKID = System.Convert.ToInt32(Defaults["CampaignID"]);

if (Defaults["BannerID"] != null && Defaults["BannerID"].ToString() != "")
intBID = System.Convert.ToInt32(Defaults["BannerID"]);

if (Defaults["DCSite"] != null && Defaults["DCSite"].ToString() != "")
strSite = Defaults["DCSite"].ToString();

if (Defaults["Keywords"] != null)
strKeywords = Defaults["Keywords"].ToString();

strPageName = "p_" + objUniversal.PageKey.ToString();
strSelectKey = objUniversal.SelectKey.ToString();
strDayName = DateTime.Now.ToString("dddd").ToUpper();

if (Defaults["Zone"] != null && Defaults["Zone"].ToString() != "")
strPageName = Defaults["Zone"].ToString();

if (Defaults["AdSpotID"] != null)
intAdSpotID = System.Convert.ToInt32(Defaults["AdSpotID"].ToString());

/* New doubleclick stuff */
//create a random number for tag
Random rnd = new Random();
string strRand = Math.Floor((Decimal)rnd.Next() * 6000).ToString();

Response.Write("\n

if (!dctile) var dctile = 1;if (!dcord) var dcord = Math.floor(Math.random()*5000);");
Response.Write("document.write('<script language=\"JavaScript\" src=\"http://ad.doubleclick.net/adj/" + strSite + "/" + strPageName + ";page=" + objUniversal.PageKey.ToString() + ";sel=" + strSelectKey + ";day=" + strDayName + ";sz=" + intWidth.ToString() + "x" + intHeight.ToString() + ";tile=' + dctile + ';" + strKeywords + "ord=' + dcord + '?\" type=\"text/javascript\"><\\/script>');dctile += 1;\n");
Response.Write("");
Response.Write("
\n");



if (DebugStatus)
Response.Write("

-- Ads End --

");

}

public int version()
{
return 2;
}

}

}

*************

I appreciate your help.


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.