Handling the XMLHttpRequest in Ajax

If you are looking to get started with learning AJAX, you probably know a little background of the technology. AJAX is not a technology in itself but a combination of other technologies that have been around for quite sometimes, namely, HTML, CSS, Javascript, XML and a few others. The combination of these technologies is what allows creating efficient dynamic web pages.

If you are a web developer, you might be familiar with the popular Javascript, HTML, etc. and while it is apparent that programming in AJAX may have a flavor of these languages, it does follow slightly different syntax. This is because the dynamic web element without the need for refreshing the page in Ajax is controlled by a function known as XMLHttpRequest and it is important to know how to use this aspect in order to code an AJAX based web application.

Handling the XMLHttpRequest object differs depending on the browser thus it may require a little more work. This difference is only in the popular Internet Explorer so it cannot be overlooked. All other popular browsers handle the object in a common method. Thus if you want to provide a common experience to all your website visitors, you will need to use a decision statement to determine the browser and then execute the different syntax depending on the browser.

In Internet Explorer the getHttpRequest (used to create dynamic pages without reloading the page) object can be initiated using the following syntax:

http = new ActiveXObject("Microsoft.XMLHTTP");

While with other browsers including Firefox, Opera and Safari the request is made like this:

http = new XMLHttpRequest();

The process of checking which browser the client is visiting the website from and using the appropriate request can be summed up in a simple function:

function getHTTPObject() {
          if (typeof XMLHttpRequest != 'undefined') {
                  return new XMLHttpRequest();
         try { 
                 return new ActiveXObject("Msxml2.XMLHTTP"); 
         } catch (e) { 
                 try { 
                       return new ActiveXObject("Microsoft.XMLHTTP"); 
                } catch (e) {} 
        return false;

var http = getHTTPObject(); 
http.open("GET", "http://example.org/test.txt", true); 
http.onreadystatechange = function() {
              if (http.readyState == 4) { 

The function is used to detect which browser is in use and execute the appropriate request accordingly. Once the function is written, the rest of the code assigns and initiates values to the variables used in the function.

The XMLHttpRequest is the main factor in Ajax programming, apart from this aspect, programming with Ajax is pretty ordinary and would seem quite familiar if you have programming experience.