Archive for March, 2009

New Formatting for XMLHttpRequest

Monday, March 30th, 2009

Recently I decided to try reducing the size of hacking the HTTP request for cross browser support in AJAX. This little snippet has been tested and is working.

// new xml http object
var xmlHttp = new XMLHttpRequest() ? new XMLHttpRequest() :
		( new ActiveXObject("Msxml2.XMLHTTP") ? new ActiveXObject("Msxml2.XMLHTTP") :
		( new ActiveXObject("Microsoft.XMLHTTP") ? new ActiveXObject("Microsoft.XMLHTTP") : null ) );

I find this new method easier to read and is much more elegant than the method bellow; which is the only method I’ve seen out there.

try{
	// Firefox, Opera 8.0+, Safari
	xml=new XMLHttpRequest();
}catch(e){
	// Internet Explorer
	try{
		xml=new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			xml=new ActiveXObject("Microsoft.XMLHTTP");
		}catch(e){
			alert("Your browser does not support AJAX!");
			return false;
		}
	}
}

I know that I am not the only who has tried to shorten this section of code. Let me know what you think or how you handle it yourself.