2LeggedSpider

Hands on AJAX

Posted in AJAX by Sumit Thomas on December 15, 2005

AJAX is one of the Buzz words in Web development nowadays, thanks to some cool implementation by Google in gmail.com.

More information on AJAX could be found here

I tried a sample implementation of AJAX. I started off by creating a Web form in ASP.NET.

The source code of the Web page is as follows:

public void Page_Load(
object sender, EventArgs e )
{
SqlConnection con = new
SqlConnection("server=(local);user id=sa;pwd=;database=northwind");
SqlCommand cmd = new SqlCommand("select * from employees order by LastName",
con);
con.Open();
SqlDataReader dr =
cmd.ExecuteReader(CommandBehavior.CloseConnection);
while( dr.Read() )
{
Response.Write( dr["FirstName"].ToString() + ", " +
dr["LastName"].ToString() + "
");
}
dr.Close();
}

Save this page as db.aspx

The code is very simple. I am connecting to the Northwind database and displaying the Employee names from the Employees table.

Now the server side page need not be a ASP.NET page, it could be PHP, ASP, JSP or any other server side script.

The source code for the client side page is as follows:

var X=null;

//Function to get the XMLHTTP Object. Gets it in a IE/Mozilla friendly way.
function
getXMLHTTP(){
var X;
//For IE
try{
X=new
ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
X=new
ActiveXObject("Microsoft.XMLHTTP");
} catch(oc){
X=null;
}
}
//For Non-IE browsers
if(!X && typeof XMLHttpRequest !=
"undefined") {
X=new XMLHttpRequest();
}
return X;
}

//This function is called in the document onLoad event to fill the DIV tag
//with the data from the server side web page.
function FillData(d)
{
//Return if the XMLHTTP object is already initialised or in use
if(X && X.readyState!=0){
X.abort()
}

X=getXMLHTTP();

d = document.getElementById(d);
eval(d).innerText = "Loading....";

if(X){

//Use the object's open method and pass the required arguments.
//First argument is the method, GET or POST
//Second argument is the web page's URL
//Third argument is to mention if the process should be asynchronous or not
X.open("GET","db.aspx",true);

// This function is called only if we get a complete response from the web page.
X.onreadystatechange=function() {

if(X.readyState==4&&X.responseText) {
// Once we get the complete response, pass the response text to the Div tag.
eval(d).innerHTML
= X.responseText;
}
};
}
X.send(null);
}

function
Fill()
{
FillData("disp");
}


<div id="disp">
</div>

Save this page as a HTML file.

Place both the files in web server and if you run the HTML file you should see the data from Employee table populating the DIV tag. This works in the latest version of IE, FireFox and Opera.

Technorati: , , ,
Tagged with: