Change Language


Follow Navioo On Twitter

Getting started with AJAX and XMLHttpRequest


One of the newest things to take the web development industry by storm is the use of AJAX (Asynchronous Javascript And XML), which uses the XMLHttpRequest object. The beauty of this new technology is it allows designers and developers to add interactive or live parts to their website without have to reload the page. This can include live information such as stock market values (the FTSE 100 is a great example as its value can change as quickly as every minute) and the number of posts on a forum. All these values could change on a page without having to refresh to page every minute.

This tutorial will hopefully give you some idea on how to use the XMLHttpRequest object in your website apps to improve user interactivity and the general functionality of your website. It is advised that you have some background knowledge of JavaScript, and for this example, PHP (or some other server-side scripting language such as Perl or ASP).

Where to begin...

The actual code that created the object is not all that difficult to grasp. There are many different variations across the internet, but my version consists of three simple JavaScript functions. I have commented throughout the functions to let you know what is going on and will explain afterwards what I am doing:



				function createRequestObject() {

   var req;

   if(window.XMLHttpRequest){
      // Firefox, Safari, Opera...
      req = new XMLHttpRequest();
   } else if(window.ActiveXObject) {
      // Internet Explorer 5+
      req = new ActiveXObject("Microsoft.XMLHTTP");
   } else {
      // There is an error creating the object,
      // just as an old browser is being used.
      alert('Problem creating the XMLHttpRequest object');
   }

   return req;

}

This function creates the initial XMLHttpRequest object. First we create an empty variable named req. Then we check whether or not the window.XMLHttpRequest object is recognised by the browser, in this case Mozilla Firefox, Apple's Safari and Opera all do. If it isnt, then the browser is more than likely Internet Explorer (version 5 and above are only capabled of using AJAX), so we use the alternative ActiveXObject("Microsoft.XMLHTTP") instead.

I have also added some error handling so if for some reason it still won't create the object, for example the are using a browser such as Internet Explorer 4 or an old version of Netscape, then it won't work.

Next, we need to add the following lines of code to create the actual object:


   
			              
// Make the XMLHttpRequest object
   var http = createRequestObject();

Sending requests using GET method

The XMLHttpRequest object (see the code above) is now created, so we can use the various to make our AJAX request in our website application by creating the sendRequest() function:



			              
function sendRequest(act) {

   // Open PHP script for requests
   http.open('get', 'examples/ajaxstart.php?act='+act);
   http.onreadystatechange = handleResponse;
   http.send(null);

}

This function uses the open() and send() functions of the our XMLHttpRequest object (stored in the http variable). We open up in this case a PHP script. This could be a achieved with virtually any server side scripting language, such as ASP or .NET, but I more comfortable with PHP, using GET (we can use POST instead, see the next section). The PHP script is then run, but not visibly in the browser. We don't send anything in the send() function because we are using GET and all the information is passed through the URL.

Sending requests using POST method

To use POST instead of GET when sending data to the PHP script, then you would rewrite the sendRequest() function to look like this:



			              
function sendRequest(act) {

   // Open PHP script for requests
   http.abort;
   http.open('post', 'examples/ajaxstart.php');
   http.setRequestHeader('Content-Type', 'application/x-www-form-
      urlencoded');
   http.send('act='+act);

}

This method is pretty much the same as using GET, but is sometimes more suitable, especially when handling forms. I will use an example below using a form to show you how it will work. I tend to use GET most of the time, as the only reason I would use POST on a normal website (without AJAX) would be because of displaying information in the URL (eg. information such as passwords passed through a GET variable would not be a good idea).

Finishing off our application

Our final function, as you may have noticed in the script above, is called handleResponse(). Its purpose is pretty obvious; it handles the response returned from the PHP script. Anything echoed or printed in that script is stored in a variable as part of the http object which we can work with later. This function is the most important. It is the one that handles the request and the one that we can edit easily to suit to the needs of our application:



			              
function handleResponse() {

   if(http.readyState == 4 && http.status == 200){

      // Text returned from PHP script
      var response = http.responseText;

      if(response) {
         // Update ajaxTest content
         document.getElementById("ajaxTest").innerHTML = response;
      }

   }

}

The if() function above inside our function checks whether or not the readyState of the XMLHttpRequest object is 4. This has many states, 0 being unintialised, 1 being loading, 2 being loaded, 3 being interactive and 4 being finished, the state we want. The http.status is the usual status returned by the server. 200 is the one we are used to, when the page is OK. You may know others such as 404, which is page cannot be found or 500, internal server error.

When everything is OK, we make a variable called response that stores the text returned by the PHP script. If this variable is true, then we find the element in the document with the ID of ajaxTest and replace the value inside with the value of response.

Putting it into practice

To assign this to an HTML object in your page, such as a button, input field or simply a link, then below is an example of how this can be done with our sendRequest() function:


 
			              
<!-- Attach the function when you click an input button -->
<input type="button" value="Send AJAX Request" id="sendButton"
   onClick="sendRequest('test1');" />

<!-- Attach the function when you change a drop down menu -->
<input type="text" value="" id="sendText" size="18" maxlength="56"
   onChange="sendRequest('test2');" />

In the first example, when you click on the button (like my demonstration below) then it will send the request with a value of 'test1' to our PHP script through GET, as in examples/ajaxstart.php?act=test1, so you can then echo something relevant from that response. The second example will do exactly the same, but when you choose an option in a drop down menu, but send a different response, this time 'test2'.

Below is the example that we went through above, using the GET method. It uses the onClick event handler of the input buttons to send a request. We then handle the response by changing the value of the ajaxTest div element with whatever the PHP script returned:

Please click one of the buttons below for a definition:


My example using the POST method is a simple form to show what can be by posting the data instead of sending it via GET. Simply put in the year than you were born and click submit.

Your year of birth:
This example has been fixed to work with Firefox 1.5 and IE5+

Taking it further

There is much more you can do with AJAX than mentioned above. Because you can send the value through annother server side script, which can be JSP, RubyOnRails, PHP, ASP, CGI or ColdFusion, etc. you can do anything you want with it there. You can store the values in a database, for example and broaden your web apps.

Please note that if you are thinking "Where's the XML?", considering it is the X in AJAX, I will probably write some tutorials for this side of it in the near future. This tutorial is to get used to the actual XMLHttpRequest object.

Ajax Javascript feed

↑ Grab this Headline Animator