Ajaxism! Making your ASP.NET application Ajax enabled. (1)


Many ASP.NET developers believe that AJAX is equal to putting an update panel on a form and using it! I do not blame those programmers because Microsoft Ajax Extensions has come to ease the process of making a web site Ajax enabled and making Ajaxing procedures transparent. However, I believe every developer must know about the Ajax itself and its mechanism. Moreover, if we know about the drawbacks of using UpdatePanel, we might decide to write our own Ajax code.

What is AJAX?

The word Ajax is the abbreviation of Asynchronous Javascript and XML. In general, it means to use XML and Javascript in order to create interactive web applications. In the classic web model, the browsers posts some data to server and server sends a resul HTML code back to the browser. To view the results, your browser has to refresh the page. This makes the whole page content be transferred from server to client. Whilst in many cases only a very small part of the page must be refreshed. For example, suppose there are two DropDownList control on a page. One for countries (ddlCountry) and one for Provinces (ddlProvince). We need to refresh the ddlProvince items according the ddlCountry selected item. Should we post back the whole page to the server? Should we send the whole page from server to client? Using Ajax we just refresh ddlProvince and fill it with proper items.

In order to read a complete description of Ajax please refer to Wikipedia here:

http://en.wikipedia.org/wiki/AJAX

How to implement Ajax?

In Ajax world, everything is based on something named XMLHttpRequest. The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page’s Client-Side and Server-Side.

How to use it?

Inside IE, XmlHttpRequest is created via an ActiveX. However other borwsers, like FireFox, has an internal mechanism to instantiate a XmlHttlRequest object. Of course IE 7 provides a FireFox-like method to create XmlHttpRequest so that we do not have to check the browser type.

In IE:

var xmlHttp = null;

xmlHttp = new ActiveXObject(‘Microsoft.XMLHttp’);

Other Browsers:

var xmlHttp = null;

mlHttp = new XMLHttpRequest();

we can write a function ( in JavaScript) to do it:

var xmlHttp = null;

function CreateXMLHttpRequest()

{

if(window.ActiveXObject)

{

xmlHttp = new ActiveXObject(‘Microsoft.XMLHttp’);

}

else

{

xmlHttp = new XMLHttpRequest();

}

return xmlHttp;

}

As I mentioned before, you may use new XMLHttpRequest(); in IE 7+.

Now we are ready to send a request to Server and get a response from it. We may use this with XmlHttpRequest.Open method. This method takes three arguments:

1-‘GET’ or ‘POST’. Which approach is used to exchange data with server.

2- The URL on server.

3- True/False. Indicates is the communication with server Asynchronous or not. If you specify True, the open method will not wait for the response.

For instance, we may write this code:

xmlHttp.Open(‘GET’, ‘FetchUsers.aspx?ID=1’,true);

Afterwards we must wait for the response from the server. We are notified of a change in XmlHttp object with “onreadystatechange” event. This event belongs to XmlHttpRequest and we have to handle it. To do this, just write a JavaScript function and assign it to this event:

xmlHttp.onreadystatechange=update;

function update()

{

//some code here

}

What does update() function do? In such a function or better say such an event handler, we must check the value of readyState property. This property belongs to XmlHttpRequest and indicates what is going on! The possible values of this property are as follows:

0 or uninitialized

Object is not initialized with data.

1 or loading

Object is loading its data.

2 or loaded

Object has finished loading its data.

3 or interactive

User can interact with the object even though it is not fully loaded.

4 or complete

Object is completely initialized.

Well, needless to say that the server response is ready-to-use only if the readyState is 4.

Inside the Update() function we can do whatever we feel like, if readyState is 4:

if (xmlHttp.readyState ==4)

{

var msg=xmlHttp.responseText;

document.getElementById(‘lblHello’).innerText= msg;

}

Please look at the above code. The code shows that we have received the server response with responseText property. We may also receive an XML formatted response with responseXML. If you might have non-English characters in your response, I strongly recommend you to pass Data in XML format with utf-8 encoding.

The 2nd line above shows that the response has been assigned to innerText property. innerText is somehow equal to .Text property of a Label or Textbox control. You may use it if your response is Plain Text only. If your response is in html format you must assign it to innerHTML property.

That is it! You may write a small JavaScript function and assign it to any desired event, like onclick, ondblclick, onmouseover,on keyup and… to invoke your Ajax code.

However we must know that where the server response comes from? As the above example shows we get the response from FetchUsers.aspx. Whatever that FetchUsers.aspx writes into its Response object will be put in responseText property of XMLHttpRequest. By the way, the overhead of .aspx pages is too much I personally prefer to use Generic Handlers (.ashx). Generic Handlers are very flexible and lightweight . Therefore I will talk about them later on separate posts.

Let’s see the rest of the tutorial in action. I have written a sample code that you may download from HERE. This ASP.NET 2.0 website get’s your name and says you hello in an AJAX way 🙂 The source of JavaScript part of this implementation is here:

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>ASPGY.WORPRESS.COM</title>
<script type=”text/javascript” language=”javascript”>
var xmlHttp = null;
function CreateXMLHttpRequest()
{
if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject(‘Microsoft.XMLHttp’);
}
else
{
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
function process()
{
document.getElementById(‘lblHello’).innerText=”loading…”;
CreateXMLHttpRequest();
if (xmlHttp != null)
{
var uname=document.getElementById(‘TextBox1’).value;
xmlHttp.onreadystatechange=update;
xmlHttp.open(‘GET’,’process.ashx?name=’+uname, true);
xmlHttp.send();
}
else
alert(‘your browser does not support ajax’);
}
function update()
{
if (xmlHttp.readyState ==4)
{
var msg=xmlHttp.responseText;
document.getElementById(‘lblHello’).innerText=msg;
}
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<span style=”font-size: 16pt; color: #ff0066″><strong>AJAX Sample</strong></span><br />
<br />
<span style=”font-size: 9pt; font-family: Tahoma”>Enter name</span>:
<asp:TextBox ID=”TextBox1″ runat=”server” onkeyup=”process()”></asp:TextBox><br />
<asp:Label ID=”lblHello” runat=”server” Font-Names=”tahoma” Font-Size=”9pt” ForeColor=”Blue”></asp:Label></div>
</form>
</body>
</html>

You may also download a PDF version of this post HERE.


Advertisements