Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

Creating an Instance of the Object Used to Make AJAX Calls

Nowadays, AJAX is a ubiquitous technology in the IT world. When you need to create the object used to send asynchronous requests to a server, you might face the browser-difference problem. Here is a JavaScript function you could use to overcome this problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// The following function creates an XMLHttpRequest object
function createHttpRequest() {
  if (typeof XMLHttpRequest != "undefined") //NOT IE {
    return new XMLHttpRequest();
  }
  else if (window.ActiveXObject) // IE {
    var sVersions = [ "MSXML2.XMLHttp.5.0",
    "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
    "MSXML2.XMLHttp","Microsoft.XMLHttp"
    ];

    //try to get an instance of the newer version.
    //If it is not available go down till the oldest one
    for (var i = 0; i < sVersions.length; i++) {
      try {
        var ret = new ActiveXObject(sVersions[i]);
        return ret;
      }
      catch (oException) {
        //Do nothing. Just go on trying with the older versions
      }
    }
  }
  //if it gets here then no version is available
  alert("XMLHttpRequest object could not be created.");
}

As you can see this function creates the correct instance of the XMLHttpRequest object. If the browser is not Internet Explorer then it just instantiates the XMLHttpRequest object, otherwise it tries to create the correct ActiveX object used by IE to represent XMLHttpRequest. In this case it tries to instatiates the object from the newer version going down till the oldest one.

Note: Finally, IE7 seems to use the same object used by other browsers, that is XMLHttpRequest. However, I advise you to use the above code just to be sure that older browser versions get the correct object in any case–provided that at least one is available!

Comments