The XMLHttpRequest Instantiation with explanations

function getXMLHTTP() {
var XMLHTTP = null;
if (window.ActiveXObject) {
try {
//this legacy approach failed, try other object
XMLHTTP = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
//ie implementation
XMLHTTP = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e) {
}
}
} else if (window.XMLHttpRequest) {
try {
//mozilla based. This line tries to create a new
//request object, but it won’t work for every browser type.
XMLHTTP = new XMLHttpRequest();
} catch (e) {
}
}
return XMLHTTP;
}

//This line asks for an instance of the request object and assigns it to
//the variable XMLHTTP
var XMLHTTP = getXMLHTTP();

if (XMLHTTP != null) {
//These parameters tell the request object how we want it to connect to the server.
//“GET” indicates how to send the data (the other option is “POST”).
//2nd parameter is the url for the serverside script that will respond to the request.
//3rd parameter, This means that the request should be asynchronous. That is, the code
//in the browser should continue to execute while it’s waiting for the server to respond.
XMLHTTP.open(“GET”, “ajax.aspx?sendData=ok”, true);

/* if want to post, which can be read using Request.Form on server side
XMLHTTP.open(“POST”, “ajax.aspx”);
XMLHTTP.onreadystatechange = stateChanged;
XMLHTTP.send(“sendData=ok&returnValue=123”);
*/

//This is the line that tells the browser what code to call
//when the server responds to the request. This is a reference to a
//function, not a function call. So make sure you don’t include any parentheses at
//the end of the function name.
XMLHTTP.onreadystatechange = stateChanged;
//You’re sending the request here, null means you’re not sending
//any extra data with the request
XMLHTTP.send(null);
}

function stateChanged() {
//readyStateis the status code message returned by the server, for example, “OK” for status 202.
//Contains information sent back by the server in XML format.
if (XMLHTTP.readyState == 4 && XMLHTTP.status == 200) {
//response TextContains textual information sent back by the server.
window.alert(XMLHTTP.responseText);
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s