Abstracting the XHR
While our basic AJAX example is functional, it is somewhat inflexible and still not perfect. By writing a function to handle the creation of the AJAX object, we can add a layer of abstraction and improve reliability.
Creating the object with try-catch statements
In the basic ajax section, we used the following code to prepare out XMLHttpRequest object:
if(navigator.appName == "Microsoft Internet Explorer") {
xhrobj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xhrobj = new XMLHttpRequest();
}While this is suitable for basic sites, it is rather unreliable, as implementations of the IE rendering engine may not use the "Microsoft Internet Explorer" application name. In addition, there is a third ActiveX Object we may need to resort to for AJAX: "Msxml2.XMLHTTP".
The most reliable way to initialise an AJAX object is therefore to attempt to create each of these in order of preference, and if one object is unavailable to try to create the next. When we try to create an object that does not exist, an error is thrown; we can safely ignore this error. Here's the code:
try {
xhrObj = new XMLHttpRequest();
} catch (e) {
try {
xhrObj=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhrObj=new ActiveXObject("Microsoft.XMLHTTP");
}
}Once this code snippet is complete, we can safely assume that the
xhrObjvariable is now a functioning AJAX object.Using a function
We can then wrap this in a function:
function ajax_object() {
try {
xhrObj = new XMLHttpRequest();
} catch (e) {
try {
xhrObj=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhrObj=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xhrObj;
}
xmlHttp = ajax_object(); // Create a new AJAX object.Abstracting AJAX requests
Now that we can control the creation of the object in a function, we should create a layer to handle the actual AJAX requests:
function ajax_request(url, data, callback)
{
var xhrobj = ajax_object();
xhrobj.open("GET", url);
xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhrobj.onreadystatechange = function()
{
if (xhrobj.readyState == 4 && xhrobj.status == 200)
{
if (xhrobj.responseText)
{
callback(xhrobj.responseText);
}
}
};
xhrobj.send(data);
}We can then easily make an AJAX request just by calling the
ajax_request()function:ajax_request("backend.php", "variable=value", function(response) {
alert(response);
});Note that we are also defining the callback function inline, with the power of functional programming.
| « AJAX Security Restrictions | XMLHttpRequest Reference » |
More AJAX Tutorials:
» Ajax Wireframing Approaches
» Five Ways to Spice Up Your Site with jQuery
» The obligatory 'My Ajax Tutorial' Post
» AJAX Accessibility for Websites
» AJAX and PHP Form Processing
» A Designer's Guide to Prototyping Ajax


