October 2017 : Online course in ASP.NET MVC / Core. Conducted by Bipin Joshi. Read more...
Registration for October 2017 batch of ASP.NET MVC / Core online course has already started. Conducted by Bipin Joshi. Book your seat today ! Click here for more details.

Using AJAX with ASP

Using AJAX with ASP.NET (Part 1)

Introduction

ASP.NET page processing model is post back based. That means in order to handle any server side event you must post the form back to the server. This event driven model is certainly powerful and rich but it has drawbacks of its own. Now a days many browsers support client side JavaScript and DHTML. AJAX model is all about making intelligent use of browser's capabilities to give better user experience. In Part 1 of this series I will explain what AJAX is with a simple example.

What is AJAX?

AJAX stands for Asynchronous JavaScript And XML. AJAX by no way is a new technology. The parts of AJAX i.e. HTML, XML, DOM, XMLHTTP and JavaScript are being used for years. AJAX refers to use of these individual pieces together.

Imagine a web form with a TextBox, a Label and a Button. The TextBox is supposed to accept a CustomerID and on the click of the button you are supposed to retrieve the total orders placed by the customer and display in the Label. How will you do it in normal way?

You will write Click event handler for the Button and inside the event handler you will write all the code to retrieve the total orders depending on the CustomerID specified in the TextBox. That means for each and every CustomerID you will cause a post back to the server. Think what will happen if your page contains lots of other controls or heavy images. Naturally the overall network traffic will be much more resulting in a poor performance.

AJAX can solve such problems. Using AJAX you don't cause frequent post backs to the server. Instead you give requests to server side resources (web forms for example) from the client browser itself. Once the request returns the data you update the controls accordingly.

On one hand AJAX can give much better user experience and performance but on the other hand you also need to worry about things such as browsers not supporting JavaScript and cross browser JavaScript.

Simple Example

To get a feel of how AJAX works we are going to develop a simple example. Our example consists of two web forms. One will have a Button and a Label. This web form will call the other web form via AJAX. The other web form will not have any UI as it is not directly displayed to the user. It will simply return a string "hello world" in it's Page_Load method. This string is displayed in the previous form when user clicks on the Button.

  • Create a new Web Application in VS.NET
  • Add two web forms to it - AJAXMain.aspx and HelloWorld.aspx
  • Drag and drop a Button and a Label on AJAXMain.aspx
  • Write following code in the Page_Load event handler of AJAXMain.aspx
    Private Sub Page_Load(ByVal sender As System.Object, 
	ByVal e As System.EventArgs) Handles MyBase.Load
        Button2.Attributes.Add("OnClick", 
	"return GetDataViaAJAX();")
        If Page.IsPostBack Then
            Label1.Text = "Server Date Time :" & DateTime.Now
        End If
    End Sub
  • Here, we added client side OnClick event handler to the Button
  • The GetDataViaAJAX() function is a client side JavaScript function that does the AJAX trick for us.
  • We then set Label's text to date time stamp. This value will never be displayed because in AJAX model post back is not happening. We are putting this code just to prove this point.
  • In the .aspx file add following JavaScript function to the <HEAD> section of the page
var obj;
function GetDataViaAJAX()
{
try
{
obj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{
obj = null;
}
}
if(obj!=null)
{
obj.onreadystatechange = ProcessResponse;
obj.open("GET", 
"http://localhost/AJAXDemo/helloworld.aspx",  true);
obj.send(null);         
}
return false;
}
  • Here, we created an instance of XMLHTTP class. This class is the key to the overall AJAX model. It is this class that makes asynchronous requests to the server resources. This class is a part of MSXML parser that ships with IE.
  • We have used try...catch blocks to take care of version differences between various versions of MSXML.
  • Once we create the instance of XMLHTTP we set its onreadystatechange property to another function called ProcessResponse.
  • The ProcessResponse function is supposed to process the return data from the page being requested.
  • We then call open() method of XMLHTTP and pass the request type (GET or POST), the url to be accessed and whether the request is to processed asynchronously or no.
  • Finally we call send() method of XMLHTTP class. In case of POST requests you may have some content which you can pass as parameter to the send() method. Since ours is a GET request we pass it as null.
  • Add following function after the above function
function ProcessResponse()
{
if(obj.readyState == 4)
{
if(obj.status == 200)
{
var retval=obj.responseText;  
alert(retval);
}
else
{
alert("Error retrieving data!" );
}
}
}
  • Here, we created a function called ProcessResponse which will be called when the helloworld.aspx returns the response.
  • Inside we check readyState property. The value of 4 indicates that the request is complete.
  • We further check the status code of the request. Status code of 200 indicates ok.
  • Finally we get the data by calling responseText method of XMLHTTP. There is one more property called responseXML that is used with XML data.
  • Now, add following code to the Page_Load event of helloworld.aspx
Private Sub Page_Load(ByVal sender As System.Object, 
ByVal e As System.EventArgs) Handles MyBase.Load
        Response.Clear()
        Response.Write("hello world")
        Response.End()
End Sub
  • Here, we first clear any response and send a simple string "hello world" using Response.Write method
  • Finally we call Response.End method to stop the further sending of response.
  • Set the AJAXMain.aspx as the startup page and run the application.
  • Click on the button and you should see a message box with "hello world". Notice that this is happening without any post back.

Code Download

The complete source code of above sample is available for download along with the article. Please see top of the article for download link.

Summary

In this article we saw what AJAX is and how it can help you build more responsive and performance rich web applications. We also saw how to use XMLHTTP component that ships with IE. In the next article I will show you how to deal with bit complex requirement tat includes XML data.

 


Bipin Joshi is a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 11 September 2005


Tags : ASP.NET AJAX JavaScript