Monday, November 4, 2013

ajax without jquery

If you just want to make Ajax calls, including jQuery can be a little heavy handed.

Here is some code I munged from this Stackoverflow question. I embedded it in the singleton we used in the global namespace (here represented by "Wrapper") and fiddled with the function signatures and location of the JSON parsing/stringify-ing 'til it matched my expectations.

Wrapper = {}; // this is just a stand in for our main singleton
Wrapper.ajax = {};
Wrapper.ajax.x = function() {
    try {
        return new ActiveXObject('Msxml2.XMLHTTP')
    } catch (e1) {
        try {
            return new ActiveXObject('Microsoft.XMLHTTP')
        } catch (e2) {
            return new XMLHttpRequest()
        }
    }
};

Wrapper.ajax.send = function(url, method, data, callback, errcallback, sync) {
    var x = Wrapper.ajax.x();
    x.open(method, url, sync);
    x.onreadystatechange = function() {
        if (x.readyState == 4) {
            if (x.status == 200)  {
                if(callback) callback(JSON.parse(x.responseText))
            } else {
                if(errcallback) errcallback(JSON.parse(x.responseText))
            }
            
        }
    };
    if (method == 'POST') {
        x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
    if(data != undefined) data = JSON.stringify(data);
    x.send(data)
};

No comments:

Post a Comment