prettify

baseline

Ajax Javascript

How to call an ajax service from a web page using
  • Javascript
  • XMLHttpRequest
  • POST
The server side implementation using C# is in another post.
Ajax.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
    <title>Ajax</title>
<script src="Ajax.js" type="text/javascript"></script>
<script type="text/javascript">
    var oM = {
        "nA": 0,
        "nB": 0,
        "nResult": 0,
        "toString": function () {
            return this.nA.toString() + "\t" + this.nB.toString();
        },
        Parse: function (oResult) {
            this.nResult = oResult[0];

        },
        Calc: function (fCb, ErCb) {
            var that = this;
            this.CalcRe = function (oResult) {
                that.Parse(oResult);
                fCb();
            };
            var sObject = "Mathematics";
            var sAction = "sum";
            ins.Post(sObject, sAction, this.toString(), this.CalcRe, ErCb);
        }
    };
    var oC = {
        Start: function () {
            $("btnSum").onclick = function () {
                oV.Read();
                oM.Calc(oV.Show);
            };
        }
    };
    var oV = {
        Read: function () {
            oM.nA = parseInt($("txtA").value, 10) || 0;
            oM.nB = parseInt($("txtB").value, 10) || 0;
        },
        Show: function () {
            $("tdSum").innerHTML = oM.nResult.toString();
        }
    };
    window.onload=oC.Start;
</script>
</head>
<body>
<table>
<tr><td><label for="txtA">1st Number</label></td><td><input type="number" id="txtA" value="7" /></td></tr>
<tr><td><label for="txtB">2nd Number</label></td><td><input type="number" id="txtB" value="11" /></td></tr>
<tr><td><button id="btnSum" style="width:100%;">Sum</button></td><td id="tdSum"></td></tr>
</table>
</body>
</html>
Ajax.js

var $ = function (sId) { return document.getElementById(sId); };
if (typeof ins !== "object") var ins={};
ins.sPostUrl = "../aj.ashx";
ins.nPostTimeout = 50000;
ins.Post = function (sObject, sAction, sData, cb, cbError) {
    //sData = ins.oUser.toString() + "\n" + sObject + "\n" + sAction + "\n" + sData;
    sData = sObject + "\n" + sAction + "\n" + sData;
    var oX = new XMLHttpRequest();
    oX.onreadystatechange = function () {
        switch (oX.readyState) {
            case 1:
            case 2:
            case 3:
                break;
            case 4:
                if (oX.status == 200) {
                    clearTimeout(oTim);
                    if (oX.responseText && oX.responseText === "{nError:1}") {
                        alert("Please Log In!");
                        //ins.oUser.Login();
                        return;
                    }
                    if (cb) {
                        var sHeader, nPos, aHeaders = 
                            oX.getAllResponseHeaders().replace("\r", "").split("\n"); 
                        var oHeaders = {};
                        for (var nHeader = aHeaders.length - 1; nHeader >= 0; nHeader--) {
                            sHeader = aHeaders[nHeader];
                            nPos = sHeader.indexOf(": "); //split nogood: Date has more ":"
                            if (nPos >= 0) {
                                oHeaders[sHeader.substring(0, nPos)] = 
                                         sHeader.substring(nPos + 2);
                            } else {
                                oHeaders[sHeader] = "";
                            }
                        }
                        var sType = (oHeaders["Content-Type"] ? 
                                     oHeaders["Content-Type"].split(";")[0] : "");
                        var oResult = null;
                        if ("application/javascript" === sType) {
                            if ((typeof JSON === "undefined") || 
                                (typeof JSON.parse === "undefined")) {
                                oResult = eval("(" + oX.responseText + ")");
                            } else {
                                oResult = JSON.parse(oX.responseText);
                            }
                            if (typeof oResult[0] === "string" && oResult[0] === "Error") {
                                if (cbError) cbError(oResult[1]);
                            } else {
                                cb(oResult);
                            }
                        } else {
                            cb(oX.responseText);
                        }
                    }
                } else {
                    if (cbError) cbError(oX.status, oX.statusText);
                }
                break;
        }
    };
    oX.open("POST", ins.sPostUrl, true);
    oX.setRequestHeader("Content-Type", "text/plain;charset=utf-8");
    oX.setRequestHeader("Content-Length", sData.length);
    oX.setRequestHeader("Connection", "close");
    oX.send(sData);
    var oTim = setTimeout(function () {
        oX.abort();
        alert("Connection Timeout!");
    }, ins.nPostTimeout);
};

No comments:

Post a Comment