Wednesday, 16 January 2013

AJAX CALLBACK USING HTTP

In this AJAX Tutorial i will try to explain "What is AJAX" & how you can start to learn AJAX from very basic. Ajax means Asynchronous JavaScript and XML. Asynchronous means that when you send a request, you wait for the response to come back, but are free to do other things while you wait. Ajax is not a new technology but in these days we found it in a new way. Currently almost all developers want to implement Ajax functionality to achieve asynchronus call back. ASP.NET gives us huge facility to implement Ajax functionality by using ScriptManager and UpdatePanel within very short time. But in this tutorial i will discuss Ajax basics menas XMLHttpRequest which is the generic HTTP client for JavaScript. To explain here i am using an example which described how to call server side aspx page using javascript. The serverside aspx page gives us the current server time & we will display the time into the page using Ajax.

Output Looks Like:


To implement the example add two page into your project. The first one contains the javascript code to call the second page using Ajax. And the second page returns server date time. You cab set any name for the first page but set the name for second aspx page is "ReceiveAjaxCall.aspx". Because we will call this page using the page name from javascript Ajax method.

Steps to call a serverside page by javascript using AJAX:
1. Declare an XMLHttpRequest object.
2. Instantiate the object.
3. Write a function to receive server side data
4. Make a call to server asynchronusly
5. Send


If you follow my code examples of first page then will get all steps one by one. The HTML markup code for first page is given below:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>XMLHTTP Test</title>

<script language="javascript" type="text/javascript">


function CallAjaxFunction()
{
var AjaxObject;

try
{
// For Other Browsers Like Opera, Mozilla Firefox, Safari
AjaxObject = new XMLHttpRequest();
}
catch (e)
{
// For Internet Explorer
try
{
AjaxObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
AjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something might wrong here
alert("Your browser does not spport XMLHTTP request!");
return false;
}
}
}

// Create a function that will receive data sent from the server
AjaxObject.onreadystatechange = function()
{
if(AjaxObject.readyState == 4) // Response came / server side processing completed
{
document.getElementById('<%= lblTime.ClientID %>').innerHTML='Current Server Date Time is: '+AjaxObject.responseText;
}
}
AjaxObject.open("GET", "ReceiveAjaxCall.aspx", true);
AjaxObject.send(null);
}
</script>

</head>


<body>
<form id="form1" runat="server">
<div>
<label runat="server" id="lblTime" style="font-family:Tahoma;font-weight:bold;color:Blue;font-size:1.2em"></label>
<br />
<br />
<asp:Button runat="server" id="cmd" OnClientClick="CallAjaxFunction(); return false;" Text="Get Server Time (Server Side Button)" />
<input type="button" onclick="CallAjaxFunction();" value="Get Server Time (HTML Button)" />
</div>
</form>
</body>


</html>

Look the difference between IE & non IE browsers ajax object instantiation block. Otherwise your page will not support cross-browser. If you look at the onreadystatechange property then you found that here i have declared a fixed value 4 to determine that the server call is completed. Yes 4 denotes that "The request is complete". Onreadystatechange has another 4 values like 0,1,2,3 denotes "The request is not initialized", "The request has been set up", "The request has been sent", "The request is in process" respectively. But we need to check only 4. When we get the value 4 then we write the server return value into our page label.

The open method is used to set the request type (GET, POST, PUT, or PROPFIND), the URL of the page being requested, and whether the call will be asynchronous or not. The basic syntax for open method is given below:

open(type,url,isAsync,username,password)

where username, password is optional.

And the the send method makes the connection to the URL specified in open.

To write the datetime in the page i added a lblTime label control and to make postback to the server i added two buttons one is HTML button & another one is server side button control.

OK now our receving data part is completed. We will go to implement second page which is called by first page through javascript XMLHttpRequest. Since we will send simple date time, just write the below codes into the page load event.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Clear();
Response.Write(DateTime.Now);
Response.End();
}
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.