Calling Global Action using Web API

Following is detail sample JavaScript code to call a global Action using Web API in Dynamics CRM.
/*
actionName: Name of action
param: param is an object that contians the parameter needed to be passed to the calling action.
e.g
var param = {
    param1: "this is string parameter",
    param2: false,// boolean
};  
*/
function callGlobalAction(actionName, param) {
    var serverURL = Xrm.Page.context.getClientUrl();
    var result = null;
    var req = new XMLHttpRequest();
    req.open("POST", serverURL + "/api/data/v8.0/" +actionName, false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                result = JSON.parse(this.response);
            } else if (this.status == 204) {
                console.log("Request executed successfully without a response");
            } else {
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };
    if (param) {
        req.send(window.JSON.stringify(param));
    } else {
        req.send();
    }
    return result;
}

No comments:

Post a Comment