The Ajax Object: XMLHttpRequest and IE's ActiveX Objects






The Ajax Object: XMLHttpRequest and IE's ActiveX Objects

Microsoft was the first company to implement XMLHttpRequest as an ActiveX object. Mozilla followed with a direct implementation of XMLHttpRequest, and other companies have responded with their own browsers: Apple and Safari, Netscape and Navigator, and Opera. Though the constructor for the objects differs between the two formats, each shares the same functionality and methods. Once the initial object is created and assigned a variable, the one cross-browser issue is resolved. But taking care of this issue isn't as simple as it first looks.

Object, Object, Who Has the Object?

Figure demonstrates one way to create an XMLHttpRequest object: using a conditional statement and testing for its existence. If it doesn't exist, the object is created as an ActiveXObject; it passes in the progID (program ID) of the ActiveX objectin this case, Microsoft.XMLHTTP. However, a possible problem with this is that the object used in the ActiveXObject method call may differ from machine to machine. Among the various versions of the object could be MSXML2.XMLHttp, MSXML2.XMLHttp.3.0, MSXML2.XMLHttp.4.0, etc.

You can try to resolve every version of the XMLHttp object, but most Ajax libraries and applications focus on just two: the older Microsoft.XMLHttp, and the base version of the newer MSXML2.XMLHttp. In addition, since Microsoft throws errors if it attempts to create an ActiveX object that doesn't exist, developers use this to implement the correct version:

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

If the first object creation doesn't work, the next is tried.

The code is now more robust but a lot longer. It begs to be enclosed in a function, with the global value set to XMLHttpRequest or false to signal that it couldn't be created. In the end, our code is modified to include the following function:

function getXmlHttpRequest(  ) {

   if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest(  );
      xmlhttp.overrideMimeType('text/xml');
   } else {
      try
        {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                xmlhttp = false;
            }
        }
   }
}

Of course, any cross-browser problems will soon be over because IE 7 supports XMLHttpRequest directly. In a few years, you can trim your code accordingly.

One other function call on the XMLHttpRequest object is to overrideMimeType. This is set to text/xml. Some browsers may require that the MIME type of the return be set to text/xml, and will fail if it isn't. You can either set the MIME type in the server application, or set the override value. Note that this is not a universally supported method.

Now that we have an XMLHttpRequest object, we'll cover the object in more detail next.

The XMLHttpRequest Methods

XMLHttpRequest is a rather simple object, with only a few methods and properties. However, it doesn't need to be complicated to provide a rather amazing amount of functionality.

Here are the methods, in the order most likely encountered in an application:


open

The syntax for open is open(method,url[,async,username,password]). The open method opens a connection to a given URL, using a specified method (GET or POST). Optional parameters are async, which sets the requests to be asynchronous (true, and default), or synchronous (false); and a username and password if the server process requires these.


setRequestHeader

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


send

The syntax for send is send(content). This is the heart and soul of XMLHttpRequest. This is where the request is sent with associated data.


getAllResponseHeaders

The syntax for getAllResponseHeaders is getAllResponseHeaders( ). Returns all HTTP response headers as a string. Among the information included is the Keep-Alive timeout value, content-type, information about the server, and the date.


getResponseHeader

The syntax for geTResponseHeader is getresponseHeader(label). Returns the specific HTTP response header.


abort

The syntax for abort is abort( ). Aborts the current request.

Some of the mystique associated with XmlHttpRequest may be removed if you consider that the functionality used to process a form using a traditional form submission is the same technology used with Ajax and XMLHttpRequest, except that the page remains during and after the process.

In the example, the request is a GET, so the web-page URL has the associated parameters added as part of the URL. If the request had been a POST, the send method would be the following:

function populateList(  ) {
   var state = document.forms[0].elements[0].value;
   var qry = "state=" + state;
   var url = 'ajax.php';
   xmlhttp.open('POST', url, true);
   xmlhttp.onreadystatechange = getCities;
   xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   xmlhttp.send(qry);
}

The content-type header is adjusted to urlencoded form, and a query is created and sent in the send operation. Other than these changes, the method is just the same as the Ajax call with GET.

When do you use POST as opposed to GET? POST has cleaner URLs than GET, which doesn't matter as much with Ajax. POST also is more secure; GET can be called directly on the web service. POST is also typically used for posting data, as compared to GET, which is used for queries.


In addition to the six methods, there are also six properties associated with XMLHttpRequest, which are given in Figure.

XMLHttpRequest properties
PropertyPurpose
Onreadystatechange

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

Has one of five values: 0 for uninitialized request, 1 for an open request, 2 for a request that has been sent, 3 for when a response is being received, and 4 for when the response is finished loading. For the most part, we're interested in a readyState of 4.
responseText

Response as text.
responseXML

Response as XML, which can then be processed as valid XML.
status

Returns server status, such as 404, 500, and, hopefully, 200 for all is well.
statusText

Text associated with status.


Again, there isn't anything complicated or complex about Ajax. Probably the only area in which additional complexity enters the equation is how the data is returned. This is covered in the next section.

If you try to run a Ajax application on your local system, you will most likely run into security restrictions. Browsers such as Firefox do not allow XMLHttpRequests on the local filesystem.




 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows