Adsence750x90

Tuesday, April 1, 2008

AJAX Example - request and response codes

The keystone of AJAX is the XMLHttpRequest object.

Different browsers use different methods to create the XMLHttpRequest object.

Internet Explorer uses an ActiveXObject,

while other browsers(Mozilla,Netscape,Opera..) uses the built-in JavaScript object called XMLHttpRequest.

To create this object, and deal with different browsers, we are going to use a "try and catch" statement.
between script tag u can write this code to detect browser
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
}

AJAX - Sending a Request to the Server

To send off a request to the server, we use the open() method and the send() method.

The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server. If we assume that the HTML and ASP file are in the same directory, the code would be:

xmlHttp.open("GET","url",true);
xmlHttp.send(null);



xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.Form_elemet.value=xmlHttp.responseText;
}
}
xmlHttp.open("GET","default.aspx",true);
xmlHttp.send(null);

Source

No comments: