ready-to-use resources, tutorials, tips and many other web development related stuff
WARNING! You probably have JavaScript disabled. Some features of this site will not work properly unless JavaScript enabled.
www.webdevelopmentstuff.com changed to www.webdevstuff.com

JavaScript XMLHttpRequest Object

XMLHttpRequest is one of the goals of AJAX technology. But what XMLHttpRequest actually is, where it comes from or how we can use it will be the content of this short post.

There are more definitions of the XMLHttpRequest. It depends on what side you are looking at from. From my side of view, the XMLHttpRequest Object is property of JavaScript Window Object.

As any other object, the XMLHttpRequest has its properties and methods. Here they are:

XMPHttpRequest PROPERTIES:

Property Description Notes
onreadystatechange Sets or retrieves the event handler for asynchronous requests. usually a function name
readyState Retrieves the current state of the request operation. returns an integer representing defined states:

0 = Uninitialized: The object has been created, but not initialized (the open method has not been called).

1 = Open: The object has been created, but the send method has not been called.

2 = Sent: The send method has been called. responseText is not available. responseBody is not available.

3 = Receiving: Some data has been received. responseText is not available. responseBody is not available.

4 = Loaded: All the data has been received. responseText is available. responseBody is available.

status Retrieves the HTTP status code of the request. returns an integer, e.g. 404 for “Not Found” or 200 for “OK”
statusText Retrieves the friendly HTTP status of the request. returns string, e.g. “Not Found” or “OK
responseText Retrieves the response body as a string. returns string
responseBody Retrieves the response body as an array of unsigned bytes. returns binary encoded string
responseXML Retrieves the response body as an XML DOM object. returns an XML document object

XMPHttpRequest METHODS:

Method Description Notes
open(sMethod, sUrl [, bAsync] [, sUser] [, sPassword]) Assigns method, destination URL, and other optional attributes of a pending request. sMethod: Required. String that specifies the HTTP method used to open the connection: such as GET, POST, or HEAD. This parameter is not case-sensitive.

sUrl: Required. String that specifies either the absolute or a relative URL of the XML data or server-side XML Web services.

bAsync: Optional. Variant that specifies true for asynchronous operation (the call returns immediately), or false for synchronous operation.

sUser: Optional. Variant that specifies the name of the user for authentication.

sPassword: Optional. Variant that specifies the password for authentication.

send([varBody]) Sends an HTTP request to the server and receives a response. varBody: Optional. Variant that specifies the body of the message being sent with the request.
abort() Cancels the current HTTP request.
setRequestHeader(sName, sValue) Adds custom HTTP headers to the request. sName: Required. String that specifies the header name.
sValue: Required. String that specifies the header value.
getResponseHeader(bstrHeader) Returns the specified response header. bstrHeader: Required. String that specifies the response header name.
getAllResponseHeaders() Returns the complete list of response headers.

We also can find an EVENT in the XMLHttpRequest:

Event Description Notes
ontimeout Raised when there is an error that prevents the completion of the request.

Here is an example of XMLHttpRequest Object using:

function moveCalendar(month, year)
{
    var xmlHttp;
    // Create xmlHttp Object
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e)
    {
        try
        {
            // Internet Explorer
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    // Event Handler - EventListener
    xmlHttp.onreadystatechange = function()
    {
        if (xmlHttp.readyState == 4) // 4: The Request is complete
        {
            document.getElementById('calendar').innerHTML = xmlHttp.responseText; // Response
        }
    }
    // Request
    xmlHttp.open("GET", "/modules/mod_calendar.php?month="+month+"&year="+year, true);
    xmlHttp.send(null);
}

Stated above example tries to create an XMLHttpRequest Object. If successfull, a function is triggered by XMLHttp state change which reacts to the request represented by last two lines of the code. PHP script (calendar module in this case) expects a GET requests and returns the HTML code of the calendar portion (a month) specified by request (month and year). This returned code is then pushed into the page code by setting the HTML DOM property innerHTML to the value of XMLHttp response.

But what is this complicated manner good for? The main advantage is that by using XMLHttpRequest Object you don’t have to reload whole page when trying to retrieve some information. There’s just small part of page changed which result in very fast, dynamic effect of updating the data. Also, pushing a data to database is carried out much effective in case of XMLHttpRequest Object use.

Coding a script using XMLHttpRequest Object can be done manually (every action is coded separately) or you can use one of the frameworks which incorporates AJAX or offers nice interface to your existing PHP code. I personally, prefer the second type, so I use the xAJAX library where an XMLHttpRequest Object should be convenient. The goal of the xAJAX object is that you don’t have to change anything in your existing application source code. Just load the library, create object, register the function or class you want to handle by AJAX and that’s it!

Finally, there should be noted that from security reasons the XMLHttpRequest Object works within a domain only! It means that call of some location outside the domain leads to security error like this:

Error: uncaught exception: [Exception... "Access to restricted URI denied"
code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)"
location: "http://www.testfiles.loc/js/testfile.js Line: 43"]

I hope, this brief intro into the XMLHttpRequest Object gave you at least basic overview of the AJAX technology.

3 Responses to “JavaScript XMLHttpRequest Object”

  1. David says:

    This was very helpful. One question: What is the difference between “GET”, “POST”, and “HEAD”?

  2. Arron says:

    Hi, I have query on this xmlHttpRequest.

    I have a rest webservice method which accepts a string parameter or XML object . How is it possible to send this string or XML object as parameter in XMLHttpRequest. Pelase help.

    Thanks

  3. Manisha Khare says:

    Can we make connection for URL like http://some link.

© 2008 - 2024, webdevstuff.com | Powered by Wordpress | Theme by Elegant Themes | Valid XHTML and CSS | Subscribe to RSS