views:

231

answers:

3

What is the easiest and safest way to retrieve XmlHttpRequest object that works across all browsers? Without any extra libraries. Is there a code snippet you use often?

P.S. I know there are tons of examples on the net, but this is precisely the reason I am asking: there are too many different examples, and I just want something simple and proven to work.

jQuery and other libraries is NOT an option. http://stackoverflow.com/questions/2450761/why-does-jquery-leak-memory-so-badly

+3  A: 

I sometimes use this snippet from quirksmode.org

But only if there's a really good reason not to use a proper library ;)

function sendRequest(url,callback,postData) {
    var req = createXMLHTTPObject();
    if (!req) return;
    var method = (postData) ? "POST" : "GET";
    req.open(method,url,true);
    req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    if (postData)
        req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    req.onreadystatechange = function () {
        if (req.readyState != 4) return;
        if (req.status != 200 && req.status != 304) {
//          alert('HTTP error ' + req.status);
            return;
        }
        callback(req);
    }
    if (req.readyState == 4) return;
    req.send(postData);
}

var XMLHttpFactories = [
    function () {return new XMLHttpRequest()},
    function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
    var xmlhttp = false;
    for (var i=0;i<XMLHttpFactories.length;i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
        }
        catch (e) {
            continue;
        }
        break;
    }
    return xmlhttp;
}
WoLpH
We are already using jQuery, however it leaks memory, which is crucial in our case. Thanks for the snippet, I'll try it out.
HeavyWave
Which browser uses Msxml3 ? I haven't seen it before.
HeavyWave
Any system that doesn't have Msxml6 available (which Microsoft.XMLHTTP will call). I know that atleast Windows 2000 SP4 has Msxml3 available :)
WoLpH
I'm not familiar with jQuery (as I use ExtJS), but it might be worth (if you do use the functions above), formulating the method names/API so it's similar to whatever javascript library you intend to eventually use, if any, to make migrating across once the memory leak has gone away easier.
Rob
@Rob, http://code.google.com/p/xmlhttprequest/ cross-browser xmlhttprequest specifically made to fight leaks. However I couldn't find any leaks with the code above either.
HeavyWave
+1  A: 

I just want something simple and proven to work.

Programmers compile working, tested, reliable, reusable code into what are called libraries or frameworks. Yet, you say yourself you don't want to use a library.

There is a list of Ajax frameworks on Wikipedia you can look at. I, and probably many other people. would recommend jQuery.

strager
http://stackoverflow.com/questions/2450761/why-does-jquery-leak-memory-so-badly
HeavyWave
@HeavyWave, How does a bug in only a recent version prevent you from using an older version of the library which doesn't have the bug (to that extend)? Also, *does it matter*?
strager
The old version still leaks. Yes it does, when you execute an ajax request 4 times a second.
HeavyWave
+1  A: 

not 100% certain of your question - but if you're asking for function to return a cross browser XMLHTTP instance - we have used this in our native ajax library for years - and never a problem in any browser

function getXMLHTTP() {
    var alerted;
    var xmlhttp;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    try {
        xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
    } catch (e) {
    try {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
    } catch (E) {
        alert("You must have Microsofts XML parsers available")
    }
    }
    @else
        alert("You must have JScript version 5 or above.")
        xmlhttp=false
        alerted=true
    @end @*/
    if (!xmlhttp && !alerted) {
        // Non ECMAScript Ed. 3 will error here (IE<5 ok), nothing I can
        // realistically do about it, blame the w3c or ECMA for not
        // having a working versioning capability in  <SCRIPT> or
        // ECMAScript.
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            alert("You need a browser which supports an XMLHttpRequest Object")
      }
    }
    return xmlhttp
}

Hope this helps (sorry for uneven indents)

plodder