AJAX XMLHttpRequest Object

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