Previous
Ajax Feedback Form 
A Gentle Introduction to Ajax
Ajax Library Explained

Ajax Code Explained

In the last page we used a function called 'XMLHTTPObject()' to do the ajax parts of the script. This page attempts to explain the inner working of this script - line by line.


function XMLHTTPObject() {

We create a function called XMLHTTPObject() - this function will return a XMLHttpRequest object based on the browser the visitor is using.


		var xmlhttp = false;

The xmlhttp variable holds the XMLHTTPRequest object. Its initial value is false - if its value is false at the end of the function, that means that the browser used by the visitor don't support advanced javascript that is necessary for AJAX apps.


	//If XMLHTTPRequest is available
	if (XMLHttpRequest) {
		try {xmlhttp = new XMLHttpRequest();}
		catch(e) {xmlhttp = false;}
	} 

The script will look for the XMLHTTPRequest support - this is supported by some browsers - Firefox, Mozilla, Opera, Safari etc. If present, the script will use this feature for AJAX.


else if(typeof ActiveXObject != 'undefined') {
	//Use IE's ActiveX items to load the file.
		try {xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");} 
		catch(e) {
			try {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
			catch(E) {xmlhttp = false;}
		}
	} else  {
		xmlhttp = false; //Browser don't support Ajax
	}

If XMLHTTPRequest is not available, the script tries to see if ActiveXObject is available on the users browser. We need ActiveX support to run AJAX scripts in Microsoft Internet Explorer. Here, two different versions of MSXML are supported - if either is present, we will have AJAX support.


	return http;
}

Here, the function returns the XMLHTTPRequest object if this feature is supported. If it is not support, false will be returned.

Previous
Ajax Feedback Form 

Comments

Anonymous at 17 Sep, 2007 06:05
Excellent tutorial for novice programmer
Reply to this.
Anonymous at 23 Oct, 2007 02:42
Hello -

This is amazing!! Thank you so much! -- However, i appear to be having a small issue. This is working just great with firefox, but on IE6 I cannot get it to work. No matter what it displays the version of the page that shows when useers do not have ajax support. Additionally, when i visit the site on IE6 there is the following error message in the corner:

Error: 'XMLHttpRequest' is undefined

If i comment out the if statement that looks for this function, then it works fine in IE, but does not work in firefox.

Any ideas?
Reply to this.
Comment


Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.