You are here: Reference > JavaScript > client-side > xml handling > objects > XMLHttpRequest

XMLHttpRequest object

Browser support:
Provides functionality to send and retrieve data from a server.
The XMLHttpRequest object is useful if you want to send and retrieve data from a server without reloading the current page. Typically used for retrieving XML files or pure text content from a server.
To send a request, create an instance of the XMLHttpRequest object first, then initialize a request with the open method, specify the necessary request headers with the setRequestHeader method and finally send the request with the send method.
The data transfer can be handled synchronously or asynchronously (see the open method).
  • In case of synchronous data transfers, the send method does not return until the response arrives. Do not use this type of data transfer if you do not want to keep the user waiting.
  • If you use asynchronous data transfer, register the onreadystatechange event before you send the request. The onreadystatechange event fires every time when the state of the request changes.

Syntax:

Methods that return the object:
new XMLHttpRequest ( )

Possible members:

Properties:
readyState
Returns an integer value that indicates the state of the request operation.
responseBody
Returns the body of the server's response as an array of unsigned bytes.
responseText
Returns the body of the server's response as a string.
responseXML
Builds an XMLDocument object from the body of the server's response.
status
Returns an integer that represents the status code of the request.
statusText
Returns a string that represents the status of the request in a friendly form.
Methods:
abort
Interrupts the current HTTP request.
addEventListener
9
Registers an event handler function (event listener) for the specified event on the current object.
dispatchEvent
9
Dispatches the specified event to the current element.
getAllResponseHeaders
Returns a string that contains all response headers.
getResponseHeader
Returns the value of the specified response header.
open
Initializes an HTTP request for sending.
removeEventListener
9
Removes the specified event handler from the current element that was registered earlier with the addEventListener method.
send
Sends an HTTP request to the server.
setRequestHeader
Adds an HTTP header with the specified name and value to the request.
Events:
onerror
Fires when an error occurs while loading an external file.
onload
9
Occurs when an object has been loaded.
onreadystatechange
Occurs when the state of the request changes.

Example HTML code 1:

This example illustrates the use of the an external XML file to insert data into a table:
Code
ajax.js
news.xml
<head>
    <script type="text/javascript" src="ajax.js"></script>
    
    <script type="text/javascript">
        var httpRequest = null;
        
        function SendRequest () {
            if (!httpRequest) {
                httpRequest = CreateHTTPRequestObject ();   // defined in ajax.js
            }
            if (httpRequest) {          
                    // The requested file must be in the same domain that the page is served from.
                var url = "news.xml";
                httpRequest.open ("GET", url, true);    // async
                httpRequest.onreadystatechange = OnStateChange;
                httpRequest.send (null);
            }
        }

        function OnStateChange () {
            if (httpRequest.readyState == 0 || httpRequest.readyState == 4) {
                if (IsRequestSuccessful (httpRequest)) {    // defined in ajax.js
                    FillTable ();
                }
                else {
                    alert ("Operation failed.");
                }
            }
        }


        function FillTable () {
            var xmlDoc = ParseHTTPResponse (httpRequest);   // defined in ajax.js
            if (!xmlDoc)
                return;

            var resTable = document.getElementById ("resTable");
            var xmlNodes = ["title", "description", "pubDate", "link"];

            var itemTags = xmlDoc.getElementsByTagName ("item");
            for (i = 0; i < itemTags.length; i++) {
                resTable.insertRow (i);
                for (j = 0; j < xmlNodes.length; j++) {
                    var recordNode = itemTags[i].getElementsByTagName (xmlNodes[j])[0];
                    resTable.rows[i].insertCell (j);
                    if ('textContent' in recordNode)
                        resTable.rows[i].cells[j].innerHTML = recordNode.textContent;
                    else
                        resTable.rows[i].cells[j].innerHTML = recordNode.text;
                }
            }
        }
    </script>
</head>
<body onload="SendRequest ()">
    <table border="1px">
        <thead style="font-weight: bold;">
            <tr>
                <td>Title</td>
                <td>Description</td>
                <td>PubDate</td>
                <td>Link</td>
            </tr>
        </thead>
        <tbody id="resTable">
        </tbody>
    </table>
</body>
Did you find this example helpful? yes no

Example HTML code 2:

This example and the next one use AJAX to submit a form without reloading the page. The two examples are similar, but the first one uses synchronous while the second one uses asynchronous data transfer. In synchronous mode, the send method of the XMLHttpRequest object waits for a reply, so the user cannot interact with the browser until the response has completed. In asynchronous mode, the send method does not wait for a reply but instead returns immediately, so it allows you to perform other operations while a time-consuming task is being performed in the background.
Code
ajax_form.js
register.php
<head>
    <script type="text/javascript" src="ajax_form.js"></script>
    <style>
        .error {
            display: none;
            color: #a00000;
            font-weight: bold;
        }
    </style>
    <script type="text/javascript">     
        function HideAllErrorFields () {
            for (var i = 1; i <= 4; i++) {
                var field = document.getElementById ("error" + i);
                field.style.display = "none";
            }
        }

        function ShowErrorFields (idsStr) {
            var ids = idsStr.split (",");
            for (var i = 0; i < ids.length; i++) {
                var field = document.getElementById ("error" + ids[i]);
                if (field) {
                    field.style.display = "block";
                }
            }
        }

        function AjaxSend (form, url, method) {
                // hide all error fields
            HideAllErrorFields ();
            
                // get message data
            var data = GetMessageBody (form);   // defined in ajax_form.js

                // send the request
            var httpRequest = CreateRequestObj ();  // defined in ajax_form.js
                // try..catch is required if working offline
            try {
                httpRequest.open (method, url, false);  // synchron
                httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                httpRequest.send (data);
            }
            catch (e) {
                alert ("Cannot connect to the server!");
                return;
            }

                // handle the response
            if (IsRequestSuccessful (httpRequest)) {    // defined in ajax_form.js
                if (httpRequest.responseText === "ok") {    // registration is successful
                    alert ("Thank you for registering");
                    /*
                        // if redirection is required
                    location.href = "/index.php";
                    */
                }
                else {  // some fields are invalid
                    ShowErrorFields (httpRequest.responseText);
                }
            }
            else {
                alert ("An error occurred while registering. Please try it again.");
            }
        }
    </script>
</head>
<body>
    This is a sample registration form.
    The username must be between 2 and 20 characters, the password must be between 6 and 20 characters.
    A user named Dottoro is already registered.
    <br />
    Try to register both valid and invalid values!
    <br /><br />
    <form onsubmit="AjaxSend (this, 'register.php', 'post'); return false;">
        User Name: <input type="text" name="userName" />
        <div class="error" id="error1">Must be between 2 and 20 characters.</div>
        <div class="error" id="error2">A user already exists with the same name.</div>
        <br /><br />
        Password: <input type="password" name="password" />
        <div class="error" id="error3">Must be between 6 and 20 characters.</div>
        <br /><br />
        Repeat Password: <input type="password" name="repassword" />
        <div class="error" id="error4">Must be the same as the password.</div>
        <br /><br />
        <input type="submit" value="Register" />
    </form>
</body>
Did you find this example helpful? yes no

Example HTML code 3:

This example is similar to the previous one, but it uses asynchronous data transfer and displays blinking text while waiting for the server response (the register_delay.php script waits two seconds before responding).
Code
ajax_form.js
register_delay.php
<head>
    <script type="text/javascript" src="ajax_form.js"></script>
    <style>
        .error {
            display: none;
            color: #a00000;
            font-weight: bold;
        }
        #progress {
            visibility: hidden;
            color: #00a000;
        }
    </style>
    <script type="text/javascript">     
        function HideAllErrorFields () {
            for (var i = 1; i <= 4; i++) {
                var field = document.getElementById ("error" + i);
                field.style.display = "none";
            }
        }

        function ShowErrorFields (idsStr) {
            var ids = idsStr.split (",");
            for (var i = 0; i < ids.length; i++) {
                var field = document.getElementById ("error" + ids[i]);
                if (field) {
                    field.style.display = "block";
                }
            }
        }

        var registering = false;
        
        function OnReadyStateChanged (httpRequest, form) {
            if (httpRequest.readyState == 0 || httpRequest.readyState == 4) {
                
                registering = false;
                StopAnim ();
                
                    // prevent memory leaks
                httpRequest.onreadystatechange = null;
                
                if (IsRequestSuccessful (httpRequest)) {    // defined in ajax_form.js
                    if (httpRequest.responseText === "ok") {    // registration is successful
                        alert ("Thank you for registering");
                        /*
                            // if redirection is required
                        location.href = "/index.php";
                        */
                    }
                    else {  // some fields are invalid
                        ShowErrorFields (httpRequest.responseText);
                    }
                }
                else {
                    alert ("An error occurred while registering. Please try it again.");
                }
            }
        }

        function AjaxSend (form, url, method) {
                // avoid resend data while registering
            if (registering) {
                return;
            }
                // hide all error fields
            HideAllErrorFields ();
            
                // get message data
            var data = GetMessageBody (form);   // defined in ajax_form.js

                // send the request
            var httpRequest = CreateRequestObj ();  // defined in ajax_form.js
                // try..catch is required if working offline
            try {
                httpRequest.open (method, url, true);   // asynchron
                httpRequest.onreadystatechange = function () {OnReadyStateChanged (httpRequest, form)};
                httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                httpRequest.send (data);
            }
            catch (e) {
                alert ("Cannot connect to the server!");
                return;
            }

            registering = true;
            StartAnim ();
        }

            // blinking text
        var animTimerId = 0;
        function StartAnim () {
            var progress = document.getElementById ("progress");
            progress.style.visibility = "visible";
            animTimerId = setInterval (RegAnim, 100);
        }
        function RegAnim () {
            var progress = document.getElementById ("progress");
            progress.style.visibility = (progress.style.visibility == "visible") ? "hidden" : "visible";
        }
        function StopAnim () {
            var progress = document.getElementById ("progress");
            progress.style.visibility = "hidden";
            clearInterval (animTimerId);
        }

    </script>
</head>
<body>
    This is a sample registration form.
    The username must be between 2 and 20 characters, the password must be between 6 and 20 characters.
    A user named Dottoro is already registered.
    <br />
    Try to register both valid and invalid values!
    <br /><br />
    <form onsubmit="AjaxSend (this, 'register_delay.php', 'post'); return false;">
        User Name: <input type="text" name="userName" />
        <div class="error" id="error1">Must be between 2 and 20 characters.</div>
        <div class="error" id="error2">A user already exists with the same name.</div>
        <br /><br />
        Password: <input type="password" name="password" />
        <div class="error" id="error3">Must be between 6 and 20 characters.</div>
        <br /><br />
        Repeat Password: <input type="password" name="repassword" />
        <div class="error" id="error4">Must be the same as the password.</div>
        <br /><br />
        <input type="submit" value="Register" />
        <div id="progress">Registering</div>
    </form>
</body>
Did you find this example helpful? yes no

External links:

User Contributed Comments

Post Content

Post Content