XML HTTP Request Object – AJAX

I thought of inditing a very basic example of AJAX which will make the new comers ease their mind. In RajiniKanth Style, I would generally say AJAX as a technique rather than being called as Technology. Its nothing but how you can use JavaScript to pull data from the server using XML HTTP Request object and then insert the data using DOM. XML HTTP Request Object

The XML HTTP Request object is used to make HTTP requests. I realised the power of the XML HTTP Request when gmail.com was lanuched. Its actually a dream come true. Why is this much spoken?

1. You can update a page without reloading the entire page.
2. You can send data to server in background.
3. You can request and receive data from server after the page has loaded.

Let us go in depth which will give you a broader idea.

Creating the Object

Its a sort of pain for developers, but you need to get it going as browsers do vary their style in creating the object. In Internet Explorer, We create the object using new ActiveXObject(“Msxml2.XMLHTTP”) or new ActiveXObject(“Microsoft.XMLHTTP”) depending upon the version of MSXML installed.

In Mozilla and Safari you use new XMLHttpRequest() IceBrowser uses yet another method the window.createRequest() method.

var httpReqObject=false;

try {
httpReqObject= new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
httpReqObject= new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (E) {
httpReqObject= false;
}
}

if (!httpReqObject&& typeof XMLHttpRequest!=’undefined’) {
try {
httpReqObject= new XMLHttpRequest();
} catch (e) {
httpReqObject=false;
}
}

if (!httpReqObject&& window.createRequest) {
try {
httpReqObject= window.createRequest();
} catch (e) {
httpReqObject=false;
}
}

We initially set the xmlhttp variable to false, If the browser Object is not being created, then it throws the appropriate error message while setting the variable to false. The Above script does for all the browsers.

Now let us see how to make a Request?

Now that you have the HTTP request object in hand, let us tell the object on what request which url you want to. A function should be called as when the request is made, and what information you want to send along in the body of the request.

// The Type of request you send and the corresponding url.
httpReqObject.open(“GET”, “test.txt”,true);

// Here we call the function and check whether the readyState is 4, then shoot the alert message.
httpReqObject.onreadystatechange=function() {
if (httpReqObject.readyState==4) {
alert(httpReqObject.responseText)
}
}
httpReqObject.send(null)

Now at the same time, i can use the status to check whether the URL exists or not.

if (xmlhttp.status==200) alert(“URL does Exists!”)

Let us jump into the well slightly in depth.  Common XML HTTP Request Object Methods.

httpReqObject.abort() will stop the current request.

getAllResponseHeaders() will return you the complete set of headers (labels and values) as a string.
When you go for a HEAD request, the server will return the headers of a resource that means you can find out the Content-Type or Last-Modified of a document without downloading.

HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Cache-Control: max-age=172800
Expires: Sat, 06 Apr 2002 11:34:01 GMT
Date: Thu, 04 Apr 2002 11:34:01 GMT
Content-Type: text/html
Accept-Ranges: bytes
Last-Modified: Thu, 14 Mar 2002 12:06:30 GMT
ETag: “0a7ccac50cbc11:1aad”
Content-Length: 52282

getResponseHeader(“headerLabel”) will return you the string value of a single header label. What is this headerLabel?

httpReqObject.getResponseHeader(“Last-Modified”)) [ This will throw you the following below ]
Last-Modified: Thu, 14 Mar 2002 12:06:30 GMT

open(“method”, “URL”[, asyncFlag[, "userName"[, "password"]]])

The Method name is GET , following with a url and boolean which indicates whether or not the request will be asynchronous. Normally the open method does accepst five parameters and there are different type of Requests. The fourth and fifth parameters are the URL user and password, respectively.

# GET
# POST
# HEAD
# PUT
# DELETE
# OPTIONS

httpReqObject.send(content)

This method accepts a single parameter containing the content to be sent with the request.

function mySubmit(id) {
var url    = “submitForm.php”;
var params = “id=” + id;

httpReqObject.open(“POST”, url, true);

//Send the header information along with the request
httpReqObject.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
httpReqObject.setRequestHeader(“Content-length”, params.length);
httpReqObject.setRequestHeader(“Connection”, “close”);

httpReqObject.onreadystatechange = onPostSubmit;
httpReqObject.send(params);

}

Here i am sending the params in the send method along with the headers. It is essential that the data returned from the server be sent with a Content-Type set to text/xml. Content that is sent as text/plain or text/html is accepted by the instance of the request object however it will only be available for use via the responseText property.

setRequestHeader(“label”, “value”)

The setRequestHeader method can be invoked to send HTTP headers with the request. The first parameter would be a strign name and the second parameter with a strign value.

httpReqObject.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);

Common XMLHttpRequest Object Properties

readyState

Object status integer:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

onreadystatechange

When the open method of httpReqObject object is invoked with a third parameter set to true, the on readystatechange event listner will be called for the following actions that change the readyState property of the object.

1. When the open method has been invoked successfully, the readyState property of the object should be assigned a value 1.
2. Once the send method has been invoked and corresponding response headers has been recieved, the readyState property should beassigned to
3. Once the HTTP response content starts loading, the readyState property should beassigned a value of 3.
4. Finally when the content has finished loading, the readyState property should be assigned a value of 4.

responseText

String version of data returned from server process

responseXML

DOM-compatible document object of data returned from server process

status

Numeric code returned by server, such as 404 for “Not Found” or 200 for “OK”

statusText

String message accompanying the status code

With this, i think i have covered to some extent of the XML HTTP Request Object. AJAX is a wonderful thing if you go on playing with it. I will get back a finishing style like RajniKanth with an example showing the power of AJAX.

Popularity: 9% [?]

About the Author

Vinothbabu has written 23 stories on this site.

In short, my name is Vinoth babu { perra kettala summa authrithala } a UI expert from India, Chennai.

One Comment on “XML HTTP Request Object – AJAX”

  • Sid wrote on 30 September, 2009, 13:10

    nice… look forward to seeing a sample in RajniKanth style…

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 HTTPguru. All rights reserved.

Our Partners:
WebHosting Jobs| UI expert | Packet Sniffer  | Mobile Home Refinancing  | Laptop LCD screens | CSS Creator| Exchange Hosting| Compare cable companies| Usa online casino | vps | Coupon Codes