Simple AJAX example in ASP.Net

What is AJAX? AJAX stands for Asynchronous JavaScript And XML. The XMLHttpRequest object present in the modern browsers helps us to create a GET or POST request asynchronously and enables us to register a callback function that gets called when a response returns from the request. The response can be in the form of a responseText or responseXML. When the response is of a text form we can just use it to display it in the browser or if it is in XML format parse the XML and display it in the browser. The following article contains a simple example to explain the above description.

Simple example of how to implement AJAX functionality in ASP.Net 2.0 This example uses pure Javascript, ASP.Net 2.0, C# and doesnt use any AJAX frameworks.

I hope this article will help beginners get a glimpse of AJAX development in ASP.Net 2.0. Not required but basic knowledge of ASP.Net and Javascript will be really helpful.

First let's write a couple of ASP.Net pages. I assume readers will have Visual Web Developer 2005 (VWD) or Visual Studio 2005 installed in your machine.

Objective: Creating a simple web page with a TextBox and a Button. The user will type in his name in the TextBox or may leave it blank. On clicking "Click Me!" button, make a AJAX call using GET or POST to the web server, retrieve the response from the server and show in the same page without any page refresh. In this case if the user types his name then the server returns "Hello " followed by the value entered in the TextBox or just simply returns "Hello Guest!"

Step 1: Fire up your Visual Web Developer or Visual Studio 2005 and create a new website and name it for e.g SimpleAjax

Step 2: Let's create a couple of ASP.Net pages

Step 2.1: Default.aspx (this gets created by default when you create a new website) This page will be the starting page and will display a simple TextBox and a Button. In this file we will also add some javascript code to send and handle the ajax request. To make code cleaner I created 2 seperate methods in javascript to perform AJAX call using GET or POST.

File Default.aspx will be...

<%@ Page Language="C#" AutoEventWireup="True" CodeFile="Default.aspx.cs" Inherits="_Default" %>

var ajaxObj;

// Change this URL to http:////AJAXRequestProcessor.aspx
var serverURL = "http://localhost:4432/SimpleAjax/AJAXRequestProcessor.aspx";

/*
* ajax_CreateXMLHttpRequest : This functions creates an XMLHttpRequest object
* based on the browser
*/
function ajax_CreateXMLHttpRequest()
{
var xmlHttpRequest = null;

/*
* For Firefox, Mozilla, Safari
*/
if (window.XMLHttpRequest)
{
xmlHttpRequest = new XMLHttpRequest();
}
/*
* For Microsoft Internet Explorer
*/
else if (typeof ActiveXObject != "undefined")
{
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

return xmlHttpRequest;
}

/*
* ajax_MakeAnAJAXGetCall : This function registers the callback function i.e ajax_CallBack
* to be invoked from getting response from the server & invokes a
* AJAX GET call to the remove server url
*/
function ajax_MakeAnAJAXGetCall()
{
ajaxObj = ajax_CreateXMLHttpRequest();
if (ajaxObj != null)
{
var URL = serverURL;
var name = document.getElementById("txtName").value;

if (name != null && name != '')
URL += '?name=' + escape(name);

ajaxObj.open("GET", URL, true);
ajaxObj.onreadystatechange = ajax_CallBack;
ajaxObj.send(null);
}

return false;
}

/*
* ajax_MakeAnAJAXPostCall : This function registers the callback function i.e ajax_CallBack
* to be invoked from getting response from the server & invokes a
* AJAX POST call to the remove server url
*/
function ajax_MakeAnAJAXPostCall()
{
ajaxObj = ajax_CreateXMLHttpRequest();
if (ajaxObj != null)
{
var URL = serverURL;
var name = document.getElementById("txtName").value;
if (name != null && name != '')
URL = 'name=' + escape(name);
ajaxObj.open("POST", serverURL, true);
ajaxObj.onreadystatechange = ajax_CallBack;
ajaxObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxObj.send(URL);
}

return false;
}

/*
* ajax_CallBack : This function is a callback function that gets called when a response
* starts receiving from the above ajax request
*/
function ajax_CallBack()
{
if (ajaxObj.readyState == 4)
{
if (ajaxObj.status == 200)
{
var ajaxResponse = ajaxObj.responseText;
var resultViewer = document.getElementById("resultViewer");
if (resultViewer != null)
{
resultViewer.innerHTML = ajaxResponse;
}
}
else
{
resultViewer.innerHTML = "Error occured!";
}
}
else
{
resultViewer.innerHTML = "Loading...";
}
}

Name:

File Default.aspx.cs (Code behind file for Default.aspx)

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnClick.Attributes.Add("OnClick", "return ajax_MakeAnAJAXPostCall();");
}
}

Step 2.2: From VWD or Visual Studio 2005, Add a New Item and choose Web Form and give the name as AJAXRequestProcessor.aspx

File AJAXRequestProcessor.aspx will be...

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AJAXRequestProcessor.aspx.cs" Inherits="AJAXRequestProcessor" %>

Untitled Page

File AJAXRequestProcessor.aspx.cs (Code behind file for AJAXRequestProcessor.aspx)

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AJAXRequestProcessor : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string name = "Guest";
if (Request.QueryString["name"] != null)
{
name = Request.QueryString["name"].Trim();
}
else if (Request.Params["name"] != null)
{
name = Request.Params["name"].Trim();
}

Response.Clear();
Response.Write("Hello " + name + "!");
Response.End();
}
}

To try this example just change the value for serverURL in the Default.aspx's javascript code to the URL according to your local settings, build the web site, Select Default.aspx in the Solution Explorer and press Ctrl+F5. The web browser will be launched with the Default.aspx page. Just enter your name or some value and click button "Click Me!". You will be greeted with a "Hello " + TextBox value or "Hello Guest!" in red instantaniously without a browser refresh.

To use POST method instead of GET, just do the following:-

- Change the following line in Default.aspx.cs
btnClick.Attributes.Add("OnClick", "return ajax_MakeAnAJAXPostCall();");

Comments

Wow, I never knew that Simple

Wow, I never knew that Simple AJAX example in ASP.Net. That's pretty interesting…