Shortest way to create an XMLHttpRequest object

This should work in everything, I think, to get an XMLHttpRequest object for JavaScript in your browser:

http = window.XMLHttpRequest ? new window.XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject("MSXML2.XMLHTTP"): null);

Of course, this only applies if you’re not using a library to make all this stuff go away, which you maybe should be. But if you’re not, this is a very short way to get the thing you need for Ajax.

6 Responses to “Shortest way to create an XMLHttpRequest object”

  1. [...] Original Article [...]

    Shortest way to create an XMLHttpRequest object
  2. What about try{} catch{} ? Don’t you need to test-instantiate the object in IE to protect against runtime errors when ActiveX is disabled?

    “which you maybe should be”

    Why’s that then..?

    brothercake
  3. brothercake: part of the reason it says “I think” up there is precisely because this is supposed to be the start of a conversation where we refine this to be the actual shortest way to do it :) Good point on ActiveX being present but disabled. I shall check that. If we have to use try/catch then we have to. Everyone’s either using a library or inventing their own (similar but different) code to do this; it’d be nice to say “*this* is the right way, do it this way” :)

    And on the libraries point, I refer the honourable gentleman to the answer I gave some moments ago :)

    sil
  4. I’ve always gone with Jim Ley: http://www.jibbering.com/2002/4/httprequest.html Note the extra XMLHTTP for a different version of MSXML; even copes with IceBrowser! On the downside, it definitely doesn’t meet your shortest requirement… ;)

    Matthew Somerville
  5. Matthew: seeing that again was what prompted me to try and come up with a short and standard one that everyone can use :)

    sil
  6. [...] Original post by sil   [...]

    of our lives » Shortest way to create an XMLHttpRequest object

Leave a Reply

OpenID is a decentralised authentication system. If you use LiveJournal or Vox you already have an OpenID; just use the URL of your homepage there. See also how to get yourself an OpenID.