xmlhttpHandler.js 3.32 KB
/**
 * An easy class to make Ajax requests with the xmlhttp object
 * @author Chris Boden
 * @version 1.0b
 * @todo Figure out if/why blnLoading is needed
 * @todo Some of the private variables need to be changable maybe just make all public
 * @todo More testing
 * @todo Make distinction between data error and exception
 */

/*@cc_on @if (@_win32 && @_jscript_version >= 5) if (!window.XMLHttpRequest)
    window.XMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP') }
@end @*/

/**
 * @constructor
 * @param {String} strURL This is the URL to pass requests to
 */
var xmlhttpHandler = function(strURL) {
    var xhrHandle   = new XMLHttpRequest();
    var strMethod   = 'POST';
    var blnAsync    = true;
    var strServer   = strURL;
    var headerLabel = 'Content-Type';
    var headerValue = 'application/x-www-form-urlencoded';

    var blnLoading = false;
    var fnCallHandle;
    var fnCallError;

    var receiver = function(rsc) {
        if (xhrHandle.readyState != 4 || !blnLoading) {
            return;
        }
        blnLoading = false;

        try {
            var objResult = eval('(' + xhrHandle.responseText + ')');

            if (objResult['status'] != 0) {
                fnCallError(objResult['data']);
                return false;
            }
        } catch (e) {
            fnCallError({message: xhrHandle.responseText});
            return false;
        }

        if (typeof fnCallHandle == 'function') {
            fnCallHandle(objResult.data);
        }
    }

    var catcher = function(o) {
        var msg = 'Unable to complete your request: "' + o.message + '"';

        if (console && console.warn) {
            console.warn(msg);
        } else {
            alert(msg);
        }
    }

    return {
        /**
         * Make a POST or GET call to the server
         * @param {function} fnHandle The function to call after the server returns
         * @param {Object} oData the data object to send to the server
         * @param {function} fnError The function to call if an error occurs (optional)
         */
        call: function(fnHandle, oData, fnError) {
            var sData = this.stringify(oData);

            fnCallHandle = fnHandle;
            fnCallError  = (fnError && typeof fnError == 'function' ? fnError : catcher);

            blnLoading = true;

            xhrHandle.open(strMethod, strServer, blnAsync);
            xhrHandle.setRequestHeader(headerLabel, headerValue);
            xhrHandle.onreadystatechange = receiver;
            xhrHandle.send(sData);
        }

        /**
         * Turns a Javascript data object into a string for the server to read
         * @param {Object} obj The object to stringify
         * @param {Boolean} child If there is further nesting
         * @returns The string to send to the server
         * @type String
         */
      , stringify: function(obj, child) {
            var str = '';
            for (var strKey in obj) {
                if (typeof obj[strKey] == 'object') {
                    str += '&' + this.stringify(obj[strKey], (child ? child + '[' + strKey + ']' : strKey));
                } else {
                    str += '&' + (child ? child + '[' : '') + strKey + (child ? ']' : '') + '=' + encodeURIComponent(obj[strKey]);
                }
            }
            return str.substr(1, str.length);
        }
    }
}