Best practice for detecting AJAX/XmlHttpRequestSupport

I am trying to update an old JavaScript function used to detect support for AJAX (i.e. the XmlHttpRequest object). I've looked online (including SO) and found various solutions but I'm not sure which is the most efficient for simply detecting support.

The current function is:

    function IsSyncAJAXSupported()
		var isSyncAJAXSupported = true;

		var xmlHttp = null;
		var clsids = ["Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
		for(var i=0; i<clsids.length && xmlHttp == null; i++) {
			try {
					xmlHttp = new ActiveXObject(clsids[i]);
			} catch(e){}

		if(xmlHttp == null && MS.Browser.isIE)
			isSyncAJAXSupported = false;
		return isSyncAJAXSupported;

In Firefox 3, the above gives errors because MS is undefined.

I realise that using a library would be better but that's not an option for the short term. We are only supporting IE6 and above + recent versions of Firefox, Safari/WebKit and Opera.

What's the best way of getting a true/false for XmlHttpRequest support?



Or rather, don't waste time doing what many other people have done better.

Try grabbing the source of jQuery or somesuch and "borrow" their methods; they've already invested the time to supporting as many browsers as possible (especially true in jQuery's case) so save yourself the time.


My preferred code for this is:

function CreateXMLHttpRequest()
  // Firefox and others
  try { return new XMLHttpRequest(); } catch (e) {}
  // Internet Explorer
  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
  //alert("XMLHttpRequest not supported");
  // No luck!
  return null;

You can easily add tests for variants of Microsoft objects...

Need Your Help

How to form a LIKE statement in SQLITE with a parameter in iphone iOS?

ios iphone sqlite parameters sql-like

Say, I have a searchfield called name. If the user types 'John' in the searchfield I should check the 'Name' field for the value "John" and select all the corresponding field values. 'John' will be...

iOS 8 Screen slides wrong direction when back button tapped

ios iphone uinavigationcontroller storyboard ios8

My application was written for iOS7 and I am trying to get it updated to iOS 8. My application is configured to only work in Landscape Left and Landscape Right orientations.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.