Tuesday, December 7, 2010

Creating an AJAX JavaScript Object



I won’t get into details about Ajax so if you want to know more read here. In order to wrap Ajax functionality in a JavaScript object we need to leverage the XMLHttpRequest object; which is now part of all modern web browsers.

XMLHttpRequest wrapper function – The only reason we need this function is to provide some sort of feature validator when initializing the XMLHttpRequest object to account for older browsers.

XmlHttpObject: function () {
                if (window.XMLHttpRequest) {
                    return new XMLHttpRequest();
                } else {//IE 5,6
                    try {
                        return new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
                            return new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (ex) {
                            return null; //Browser doesn't support AJAX
                     }
                }
          }
}

Creating the JSON structure for our AJAX object

var DeveloperCaster = {
        Ajax: {
            Vars: {
                OnResponse: null,
                XmlHttp: null,
                RequestFormat: 'Text'
            },
            XmlHttpObject: function () {

            },
            Request: function (_params) {


                }
            },
            OnStateChange: function () {

            },
            Xml: {
                Parse: function (text)  

            }
        }
  
};

I am using four functions and three variables to create the AJAX object.

Variables:
OnResponse – This is a placeholder for the function that will receive the request result in the client side.
XmlHttp – This is the global pointer to the XMLHttpRequest object
RequestFormat – Flag to decide which format (XML or TEXT) our OnResponse object is expecting.

Functions:
XmlHttpObject - Initialize XMLHttpRequest object
Request - Initiate request
OnStateChange - Handle responses
Xml.Parse - Parse text to XML


Parameters

This object is expecting the following parameters in JSON notation:
url –  request url
format – either ‘Text’ or ‘Xml’
onresponse – the function that will handle the response
Example:
var _params = {
            url: ‘’,
            format:'Text'
            onresponse: function (result) {

            }
        }


So, here is all put together:

var DeveloperCaster = {
        Ajax: {
            Vars: {
                OnResponse: null,
                XmlHttp: null,
                RequestFormat: 'Text'
            },
            XmlHttpObject: function () {
                if (window.XMLHttpRequest) {
                    return new XMLHttpRequest();
                } else {//IE 5,6
                    try {
                        return new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
                            return new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (ex) {
                            return null; //Browser doesn't support AJAX
                        }
                    }
                }
            },
            Request: function (_params) {
                if (typeof (_params.url) != 'undefined') {
                    //Initialize XmlHttpRequest object
                    DeveloperCaster.Ajax.Vars.XmlHttp = DeveloperCaster.Ajax.XmlHttpObject();
                    if (typeof (_params.onresponse) != 'undefined') {
                        DeveloperCaster.Ajax.Vars.OnResponse = _params.onresponse;
                    }
                    //Check for request format
                    if (typeof (_params.requestFormat) != 'undefined') {

                        DeveloperCaster.Ajax.Vars.RequestFormat = (_params.requestFormat == "Xml" ? "Xml" : "Text");
                    }
                    //Send request
                    DeveloperCaster.Ajax.Vars.XmlHttp.onreadystatechange = DeveloperCaster.Ajax.OnStateChange;
                    DeveloperCaster.Ajax.Vars.XmlHttp.open("Get", _params.url, true);
                    DeveloperCaster.Ajax.Vars.XmlHttp.send(null);

                }
            },
            OnStateChange: function () {
                if (DeveloperCaster.Ajax.Vars.XmlHttp.readyState == 4) {
                    if (DeveloperCaster.Ajax.Vars.XmlHttp.responseText.length > 0) {
                        var result = "";
                        var _status = DeveloperCaster.Ajax.Vars.XmlHttp.status;

                        if (DeveloperCaster.Ajax.Vars.RequestFormat == "Text") {
                            //Text
                            result = DeveloperCaster.Ajax.Vars.XmlHttp.responseText;
                        } else {
                            //XML
                            result = DeveloperCaster.Ajax.Xml.Parse(DeveloperCaster.Ajax.Vars.XmlHttp.responseText);
                        }
                        if (_status == 200) {
                            if (typeof DeveloperCaster.Ajax.Vars.OnResponse == "function") {
                                DeveloperCaster.Ajax.Vars.OnResponse(result);
                            }
                        }
                        //TO DO: Handle error is status is different than 200
                    }
                }
            },
            Xml: {
                Parse: function (text) {//text to xml object
                    var xmlDoc;
                    if (window.DOMParser) {
                        xmlParser = new DOMParser();
                        xmlDoc = xmlParser.parseFromString(text, "text/xml");
                    } else { // Internet Explorer
                        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                        xmlDoc.async = "false";
                        xmlDoc.loadXML(text);
                    }
                    return xmlDoc;
                }
            }
        }
  

    };


Usage:

To initiate a request 

 DeveloperCaster.Ajax.Request({
            url: '',
            format:'Text'
            onresponse: function (result) {
                
            }
 });



Compress this code at jscompressor.com


No comments:

Post a Comment