Learning AJAX: Lesson 3 - XMLHttpRequest
Posted on Thursday, July 12th, 2007
After setting out the groundwork for my AJAX example by creating a random quote generator in PHP then using the DOM to add a link that will perform the AJAX function, I am now ready to start communicating with the server and loading up data without refreshing the page. To do so I need to get to grips with the XMLHttpRequest object.
A Bit Of Background
XMLHttpRequest is not yet a W3C standard, but there is a working draft. It was first implemented by Microsoft in Outlook before making its way to Internet Explorer 5 as an ActiveX Object. Then the Mozilla project got their hands on it, implementing it as a native browser object in Mozilla. The other browsers fell in line soon after. It is now the basis of AJAX and powers most of the web applications available online today.
Sadly, even having pioneered this object, Microsoft’s Internet Explorer tends to make life difficult for developers because XMLHttpRequest is an ActiveX object (except in IE7 where it is now a native object). To create one you need the following javascript:
var XHR = new ActiveXObject("Microsoft.XMLHTTP");
All other browsers that support XMLHttpRequest require the following:
var XHR = new XMLHttpRequest();
Once you have your XMLHttpRequest object, the methods are all the same, so it is best to create a function that returns one regardless of browser. I have done this using try and catch, try to create the native object first and, if that doesn’t work, the ActiveX version, if neither work I am going to return false so that I can halt the script in another part.
Cross Browser XMLHttpRequest
function XHR() {
try { // try the native object
return new XMLHttpRequest();
}
catch(e) {
try { // then try the ActiveX object
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) { return false; }
}
}
The final part of this mini series will be posted shortly, where I finish off my example by using the XMLHttpRequest to get my data from the server.
If you enjoyed this post, why not subscribe to Unintentionally Blank
1December 21st, 2007 at 10:22 am
SD Says:Good lessons, I’ve learned a lot about AJAX and got some questions answered that I had along the way.
2July 7th, 2008 at 2:40 pm
mark.lim Says:wow, i ‘m interested in AJAX with php,thanks for basic lesson