AJAX Intro

AJAX Request Build

AJAX Examples





AJAX XMLHttpRequest Object - Create, Send & Get Response


What is Ajax XMLHttpRequest object?

XMLHttpRequest object is an API for fetching any text base format data, including XML without user/visual interruptions.
All most all browser platform support XMLHttpRequest object to make HTTP requests.


AJAX XMLHttpRequest Object

Using Ajax XMLHttpRequest object you can make many things easier. So many new things can't possible using HEAD request.

This object allows you to making HTTP requests and receive responses from the server in the background, without requiring the user to submit the page to the server (without round trip process).

Using DOM to manipulate received data from the server and make responsive contents are added into live page without user/visual interruptions.

Using this object you can make very user interactive web application.

Following are sequence of step for working with XMLHttpRequest object:

  • Define instance of this XMLHttpRequest.
  • Create a asynchronous call to a server page, also defining a callback function that will automatically execute when the server response is received.
  • Callback function getting server response.
  • DOM manipulate received data and added into live page.

Define instance of this XMLHttpRequest object

Create new instance of the XMLHttpRequest object, using new keyword,

var xhr = new XMLHttpRequest();

Microsoft Internet Explorer 6 or earlier version, you may not able to deal with XMLHttpRequest object. Use following

var xhr = new ActiveXObject("Msxml2.XMLHTTP");
var xhr = new ActiveXObject("Microsoft.XMLHTTP");

So now our example code is implemented using try catch block,

<script type="text/javascript">
    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(exception) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Your browser does not support XMLHTTP Request...!");
    }
</script>

Initialize open() method

Now we can initialize open() method along with required parameter and optional parameter.

Syntax :

open( "method",  "URL" [ , asynchronous_flag [ , "username" [ , "password" ] ] ] )

Parameter Description :

Parameter Required? Description
method required Specifies the HTTP method.
Valid value : GET, POST, HEAD, PUT, DELETE, OPTIONS
URL required Specifies URL that may be either relative parameter or absolute full URL.
asynchronous_flag optional Specifies whether the request should be handled asynchronously or not.
Valid value : TRUE, FALSE       Default value : FALSE
TRUE means without waiting for a response, next code processing to execution queue on after the send() method.
FALSE means wait for a response after the next code processing.
username optional Specifies username of authorize user otherwise set to null.
password optional Specifies password of authorize user otherwise set to null.
<script type="text/javascript">
    ...
    ...
    xhr.open("GET", "demo_textfile.txt", true);    // Make sure file is in same server
</script>

Request send using send() method

Finally send() method execute to send it along with above specified parameters.

Syntax :

xhr.send();

Example :

<script type="text/javascript">
    ...
    ...
    xhr.send(null);
</script>

onreadystatechange Event To Set Callback Function

Before you calling send method, Using onreadystatechange event to set callback (handler) function to be executed when the status of the request changes,

Syntax :

xhr.onreadystatechange = function() {
    ......
};

Response text received from server that data assign into textarea tag using DOM.

Example :

<script type="text/javascript">
    ...
    ...
    xhr.onreadystatechange = function(){ 
        document.getElementById("textArea").value = xhr.responseText;
    };
</script>

Simple Example Code

<html>
<body>
    <script language="javascript" type="text/javascript">
    function send_with_ajax(){
        if (window.XMLHttpRequest || window.ActiveXObject) {
            if (window.ActiveXObject) {
                try {
                    xhr = new ActiveXObject("Msxml2.XMLHTTP");
                } catch(exception) {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }
            } else {
                xhr = new XMLHttpRequest(); 
            }
        } else {
            alert("Your browser does not support XMLHTTP Request...!");
        }

        xhr.open("GET", "demo_textfile.txt", true);    // Make sure file is in same server
        xhr.send(null);
        
        xhr.onreadystatechange = function(){ 
            document.getElementById("textArea").value = xhr.responseText;
        };
    }
    </script>
    
    <button onClick="send_with_ajax()">Get Contain</button><br />
    <textarea id="textArea" cols="40" rows="5"></textArea>
</body>
</html>

Run it...   »

Example Result:


XMLHttpRequest Methods

setRequestHeader : After requested URL open, use setRequestHeader to provide any optional HTTP headers for the request.

Syntax :

setRequestHeader("label", "value");

Example :

xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("User-Agent", "navigator.userAgent");

abort : abort method you can abort the request.

Syntax :

abort();

Example :

xhr.abort();

getResponseHeader : getResponseHeader method you can get the value of the specified HTTP header.

Syntax :

getResponseHeader(header_name);

Example :

var xhr_header = xhr.getResponseHeader("Content-Type");

Run it...   »


getAllResponseHeaders : getAllResponseHeaders method you can get the all values of HTTP headers as a string.

Syntax :

getAllResponseHeaders();

Example :

var xhr_header = xhr.getAllResponseHeaders();

Run it...   »


Property

onreadystatechange : Before you calling send method, Using onreadystatechange event to set callback (handler) function to be executed when the status of the request changes,

Syntax :

xhr.onreadystatechange = function() {
    ......
};

readyState : readyState property returns the status of the request.

Different States :

Constant Name State Value Description
UNSENT 0 uninitialized open() method has not been called.
OPENED 1 unsend send() method has not yet been called.
HEADERS_RECEIVED 2 send send() method has been called and headers and status data are available.
LOADING 3 receiving Data receiving from server and responseText holds the receiving data.
DONE 4 completed Ajax request finished.

Syntax : readyState property you can get current state

var current_state = xhr.readyState;

Example : You can use either constant name or state value.

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
     }
};

Run it...   »

xhr.onreadystatechange = function() {
    if (xhr.readyState == xhr.DONE) {
        alert(xhr.responseText);
     }
};

Run it...   »

Alternative way, If you concern about only state = 4 (DONE), use the onload event

xhr.onload = function() {
    ...
};

Run it...   »


status : When a request is received on server, Server return the HTTP status code using status property. for example, status code 200 for Ok, 408 for Request timeout, 404 for Request not found.

Syntax :

var xhr_status = xhr.status;

Example :

if (xhr.readyState == xhr.DONE){
    if ((xhr.status == 200) || (xhr.status == 0)){
        alert(xhr.status);
    }
}

Run it...   »


statusText : Same as above server return HTTP status string Request ok for 200, Request timeout for 408, Request not found for 404.

Syntax :

var xhr_statustext = xhr.statusText;

Example :

if (xhr.readyState == xhr.DONE){
    if ((xhr.status == 200) || (xhr.status == 0)){
        alert(xhr.statusText);
    }
}

Run it...   »


responseText : Requested response return as a string data as a string object.

Example :

var xhr_responseText = xhr.responseText;

Run it...   »


responseXML : Requested response return as a XML data as a XML object.

Example :

var xhr_responseXML = xhr.responseXML;

Run it...   »


responseBody : This property is use when XHR object created as a ActiveX component (for IE 5 & 6).

Example :

var xhr_responseBody = xhr.responseBody;