Carina Nebula

XMLHTTPRequest


Have you ever been browsing facebook, GMail, iGoogle or your favourite news or sports site and wondered just how the content can refresh without refreshing the whole page? If you're not a programmer or a web developer (or if you already know how it works) then probably not. For everyone else, here is a brief tutorial on how these sites work and how to utilize XMLHTTPRequest in your own pages.




Contents

  1. Foreword
  2. What is XMLHTTPRequest?
  3. History
  4. Let's Get to It
  5. Breakdown of a Request
  6. Sources and Links

Foreword

This tutorial has been tested in Opera, Safari, Firefox and IE6/7 (you need to allow ActiveX controls for IE) and worked correctly. If you have problems please email me and let me know what browser you are using.

Back to Top


What is XMLHTTPRequest?

XMLHTTPRequest is a Javascript object that can be used to make requests to a server for content without having to reload the entire page. This is beneficial because it cuts down on bandwidth and allows for more dynamic web pages. The main drawback is that it is not officially standardized (as of April 2008) and it requires a browser with an enabled (and supported) client-side scripting language such as javascript. That said, there is a request for comment (RFC) and a Working Draft specification for the object in place. Most "modern" browsers support this object including Opera, Safari, Firefox, Konqueror, IceBrowser and Internet Explorer and it has been around long enough for the pseudo-standard to have caught on. Also it should be noted that though it has XML in the name it can be used to get HTML data (and other types of data) as well.

Back to Top


History

The concept of the XMLHTTPRequest object was first created by Microsoft. Their version was called "XMLHTTP" and it was originally used for Outlook Web Access 2000. This started out only being supported by IE but eventually it started catching on and was supported by more and more web browsers. Now it has taken its form in different objects within most browsers but each object has roughly the same methods and is used the same way.

Back to Top


Let's Get to It

So lets get right into it! The object takes different forms/declarations depending on the browser you are using so you should use the following javascript code to implement it with some compatibility in mind. Note: For maximum compatibility, you should check to see if javascript is enable and provide some other way to display the content on the page.

var xmlhttpfound = false; //boolean var to tell if XMLHTTPRequest has been loaded.
var xmlhttp; // Set the xmlhttp variable to false
//Turn on compiler conditions and execute only if javascript is a certain version
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
// Try to create objects (IE only)
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  xmlhttpfound = true;
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   xmlhttpfound = true;
  } catch (E) {
   xmlhttpfound = false;
  }
 }
@end @*/
//If the objects couldn't be created, create for most other browsers.
if (!xmlhttpfound && typeof XMLHttpRequest != 'undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
		xmlhttpfound = true;
	} catch (e) {
		xmlhttpfound = false;
	}
}
//If that didn't work try it for IceBrowser
if (!xmlhttpfound && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
		xmlhttpfound = true;
	} catch (e) {
		xmlhttpfound = false;
	}
}

OK. Now that we have the object created (hopefully, xmlhttpfound == false if it didn't work). Let's do something with it!

function xmlRequest(url) {
  if (xmlhttpfound) { //Check to make sure the object exists
    xmlhttp.open("GET", url, true); //Open a request to the file
    //Create a function that will check the ready state when it changes
    xmlhttp.onreadystatechange = function() {
      //Only execute when the ready state is done loading (== 4)
      if (xmlhttp.readyState==4) {
        alert(xmlhttp.responseText) //Return the content in a message box
      }
    }
    xmlhttp.send(null)
  }
}

You can see an example of this by clicking this link: Example Request The text file is located here: testrequest.txt
This example will display some text from a file located within the same directory as the script it was run but it is not limited to the same directory at all. You can pass full URLs or script names and achieve the same results. Also, you don't have to return it to an alert box. You can return the results to any spot. Take the following text box for example. If you click the "Example 2" button, the file http://tutorials.drackir.com/xmlhttprequest/example2.txt will be downloaded and the contents will be displayed in the text box.

Form code:

<textarea name="example2" id="example2" rows="3" cols="25"></textarea>
<button onclick="loadexample2();">Example 2</button>

The function used is as follows:

function loadexample2() {
  if (xmlhttpfound) { //Check to make sure the object exists
    url = "http://tutorials.drackir.com/xmlhttprequest/example2.txt"; //Set the file name
    xmlhttp.open("GET", url, true); //Open a request to the file
    //Create a function that will check the ready state when it changes
    xmlhttp.onreadystatechange = function() {
      //Only execute when the ready state is done loading (== 4)
      if (xmlhttp.readyState==4) {
        //Return the content in a text box where the id = "example2"
        document.getElementById('example2').value = xmlhttp.responseText;
      }
    }
    xmlhttp.send(null)
  }
}

Back to Top


Breakdown of a Request

As I'm sure you noticed by the examples above, there are three main methods used for a typical request.

  1. xmlhttp.open(<Method>, <URL>[, <ASync>][, <Username>][, <Password>]);
    This method opens the link to the file or URL.
    The Method parameter can be "GET", "POST", "HEAD", "PUT", "DELETE" or any HTTP method.
    The URL parameter is the link to the script or file you want to connect to. Note: If you are connecting accross sites, browsers may treat this as a security risk and not allow the script to execute.
    The ASync parameter is a boolean value that specifies whether the transfer should be asychronous or synchronous. If it is set to true, the script will continue to execute even if the file is not completely transferred. If it is false (default) the script will not continue past the send() method until the file has completed downloading.
    The Username and Password parameters can be used if a file/site requires validation.
  2. xmlhttp.onreadystatechange = function() {
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState==4) {
          // Code here...
    	  //xmlhttp.responseText returns the text data.
        }
      }
    }
    This can be set to a predefined function or the function can be declared anonymously as in the code above. Basically, the onreadystatechange will execute when something changes with the readystate property of the xmlhttp object. This specific code checks to see if the request has completed and the data is there. The possible readystate values are:
    • 0 = uninitialized - open() has not been called.
    • 1 = open - send() has not been called.
    • 2 = sent - send() has been called, headers and status are available.
    • 3 = receiving - The file is downloading. responseText holds partial data except in IE [3])
    • 4 = loaded - File downloaded.
  3. xmlhttp.send(<Content>)
    The send method is used to actually send the request to the server.
    The Content parameter is used to actually send content (ie. form data, headers, etc.) to the page.

Back to Top


Sources and Links

The following links were used as references for this tutorial:



Back to Top



Copyright © 2008 Richard Marskell