The XMLHttpRequest Object Structure

The W3C, the organization responsible for most of the specifications we use in our web applications, is currently working on a standard definition of the XMLHttpRequest object. The latest working draft (at the time of this writing) is dated September 2006 and can be examined at http://www.w3.org/TR/XMLHttpRequest. we'll focus on the most important and common functionalities.

The XMLHttpRequest object is quite simple. The following methods are available in all of the target browsers:

open

The syntax is open(method,url[,async,username,password]). This method opens a connection to the given URL using the specified method (such as GET or POST).Optional parameters are async, a boolean value that sets the requests to be asynchronous ('true') or synchronous ('false'), and a username and password if required by the server process. If the async parameter is not provided, the request is asynchronous by default.

setRequestHeader

The syntax is setRequestHeader(label,value). This method adds a label/value pair to the header in the request.

If you are sending data to the server with a POST request, you need to set the value of the "Content-type" header to "application/x-www-form-urlencoded":

A Ajax POST request looks like this:

var request = getHTTPObject();
if (request) {
request.onreadystatechange = doThis;
request.open("POST", "serv.asp", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("name=AJAX+GUY&message=Welcome+to+AJAX");
}

send

The syntax is send(content). This method is used to send the request with any associated data. If the request is made using an HTTP method such as POST, where parameters aren't attached to the URL, all required parameters are passed using this method; otherwise, the content is set to null.

The open method specifies the details of an Ajax request, but it doesn’t initiate the request. Use the send method to fire off a request that you have prepared using the open method.

The send method takes a single argument. You can pass it a string of data that will then be sent to the server.

If you are using the GET request method, don’t send any data. Instead, pass a value of null to the send method.

A Ajax GET request looks like this:

var request = getHTTPObject();
if (request) {
request.onreadystatechange = doThis;
request.open("GET", "serv.asp", true);
request.send(null);
}

We use the POST request method to send data to the server using a query string like this:

name=AJAX+GUY&message=Welcome+to+AJAX


getAllResponseHeaders

The syntax is getAllResponseHeaders( ). This method returns all HTTP response headers as a string. Among the information included is the keepalive timeout value, content type, information about the server, and date.

getResponseHeader

The syntax is getResponseHeader(label). This method returns the specific HTTP response header identified by label.

abort

The syntax is abort( ). This method aborts the current request.



XMLHttpRequest also has the following properties:

onreadystatechange

This property holds a handle to the function that will be called when the ready state of the request changes.

If you attach a function to the onreadystatechange event handler, that

function will be executed every time the server pings the client with an

update. Here’s an example:

var request = getHTTPObject();

if (request) {

request.onreadystatechange = doThis;

}

I’m assigning a reference to a function called doThis to the

onreadystatechange event handler. The doThis function will be

executed every time the readystatechange event is triggered.

readyState

The readyState property indicates at what point the XMLHttpRequest object is with regard to sending/receiving data.
This property has one of five values:

0 for uninitialized,
1 for an open request,
2 for a request that has been sent,
3 when a response is being received,

and 4 when the response is finished loading. For the most part, we're interested in a readyState of 4.

We can compare the value of the readyState property to the number four using a simple if statement:

function doThis() {

if (request.readyState == 4) {

// do This with the response

}

}

The doThis function will be executed more than once because it has been assigned to the onreadystatechange event handler:

request.onreadystatechange = doThis;

Every time the readyState property changes, doThis is executed, but the if statement in the function ensures that nothing will happen until readyState has a value of 4.

responseText

This property specifies that the response will be formatted as a text string(a String of HTML, or XML, or just text).

function doSomething() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
alert(request.responseText);
}
}
}

The responseText property is available when the readyState property reaches four, indicating that the Ajax request is complete.

responseXML

Use this property to format the response as XML(XML document object). If the response is not XML, this property will be empty.

Implementations of XMLHttpRequest in all major browsers require the HTTP response’s Content-Type to be set properly in order for the response to be handled as XML. Well-formed XML, returned with a content type of text/xml (or application/xml, or even application/xhtml+xml), will properly populate the responseXML property of an XMLHttpRequest object; non-XML content types will result in values of null or undefined for that property.

status

This property refers to the server status, such as 304, 400, 404, 500, and 200, when the request is successful.

The most important header sent with any response from a Web server is the status code. This three-digit numerical value, which the server sends with every response to a request, is part of the HyperText Transfer Protocol (HTTP) that drives all communication on the Web. Some Status Codes are:

404 - Not Found

403 – “Forbidden

500 - “Internal Server Error

200 – “OK

304 - Not Modified

In the XMLHttpRequest object, the status code sent by the server is available as a property called status. By comparing this property to a value of 200, you can be sure that the server has sent a successful response:

function doThis() {
if (request.readyState == 4) {
if (request.status == 200) {
// the response was sent successfully
}
}
}

The first if statement within the doThis function compares the readyState property to a value of 4.When that evaluates to true, meaning that the response is finished being sent, the second if statement is executed.

statusText

This property specifies the text message associated with the status.


We've gone so far, let's jump to AJAX Programming,

Here's a sample Program Using XMLHttpRequest.


AJAX real time examples by Google Suggest

Welcome to AJAX. It’s a very exciting technology, very impressive and the matter of fact I believe with this is future of web applications is based on AJAX. Using AJAX, allows you to check and download data behind the scenes in your web browser, Which makes your web browser look a lot more like a true desktop application because instead of having to get a four web page refresh, you can automatically download data behind the scenes and display it, work with it, handle it, show it to the user.




For example, take a look at this new google suggest page, which you seen here in image, just visit google suggest page, while you are reading this. You can enter a search term here, for example, searching for AJAX, I enter ‘a’ as you see what happens here is that the web page has checked in behind the scenes with the server “google server” and has collected matches, popular matches to my partially entered search term. “a” for ajax and suggest them, so if you keep typing j for ajax, then you see there is while the terms are been selected is ajax with 3,840,000 results. So it’s very impressive display and or if you do selected, you are taking directly to the google page for AJAX.



You can find all matches to ajax on the page and most impressive is are you are going to do enter search term or partial search terms and behind the scenes browser checks with google website using AJAX technology, downloads possible matches to term to display them for your selection. When you select the term, you go to directly to the google webpage.

That’s the example of AJAX, because it does it behind the scenes checks the server, downloads data, and displays it to you without causing a page refresh.

In old days, used to have page refresh every time we want to display the new data, and that keeps the web a very fracture feeling because whole entire page have been refreshed if you want to check for new data, and now you don’t have to cause page refresh and all are exciting technology using AJAX, because you no longer have to cause a page refresh instead you can update the parts of the page you want, and work with the server behind the scene. That makes AJAX applications see lot more like desktop applications than web applications.

That’s the instructions for AJAX and we’re talking about AJAX is a terrific technology.

instantiating an instance of XMLHttpRequest using javascript's try…catch

If Old version browsers (Internet Explorer 5 for Mac) doesn’t support ActiveX object for Ajax
The getHTTPObject function throws an error in that browser.

JavaScript has a useful control structure for situations like this called the
try...catch statement.It looks at the user-agent string of the browser and check
its name and version number. This is called browser sniffing. We can use you can use object detection to test only for the existence of ActiveX, not for a particular type of ActiveX object.
Using try…catch block statement, we can execute the code, if it doesn’t work, you can catch the error. The error won’t be displayed in the browser.

if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}

The try block contains the attempt to assign an instance of the ActiveX
object to the variable xhr. If that doesn’t work, the catch block sets the
value to false.
The try...catch statement can be used to refine the getHTTPObject function
even further. Later versions of Internet Explorer can use a newer ActiveX
object to handle Ajax. Using a series of try...catch statements, you can
attempt to use the newest version and, if that fails, fall back to the older way:

if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}

The finished function look like this:


function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}
return xhr;
}

After handling exception, we are instantiating an instance of XMLHttpRequest. Once we’ve created an object with getHTTPObject, its methods and properties will be the same regardless of whether it’s native or an ActiveX object.

Useful Links on Adobe Flex

Your Ad Here

Latest Books on Adobe Flex