The XMLHttpRequest Object Sample

Ajax using the XMLHttpRequest Object

Open a notepad, Copy & paste the below content , and save the file as AjaxForms.htm

Save it to IIS folder , by default this is c:\\Inetpub\wwwroot.

<html>
<head><title>Techupdate</title>
<script language="javascript">
function ajaxprocess()
{
var httpRequest;
try
{
// Browser support for Firefox, Opera 8.0+, Safari
httpRequest=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
}
httpRequest.onreadystatechange=function()
{
if(httpRequest.readyState==4)
{
document.getElementById('txtname').value="";
document.getElementById('txtname').value=httpRequest.responseText;
}
}
httpRequest.open("GET","AjaxPage.aspx",true);
httpRequest.send(null);
}
</script>
</head>
<body>
Date Time : <input type="text" id="txtname"/>
<input type="button" value="Refresh" onclick="ajaxprocess();"/>
</body>
<html>

The readyState Property holds the status of the server's response

The readyState property values

State Description

0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete


The onreadystatechange property stores your function that will process the response from a server

The data sent back from the server can be retrieved with the responseText property

The ServerSide Processing

Open a notepad, Copy & paste the below content , and save the file as AjaxPage.aspx

Save it to IIS folder , by default this is c:\\Inetpub\wwwroot.

<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.ToString());
}
</script>


Open Browser , In the address bar type http://localhost/ AjaxForms.htm

Click on refresh button