Skip to main content

ServiceNow GlideAjax: 4 approaches (single value, multiple values)

ServiceNow GlideAjax: 4 approaches (single value, multiple values)

  • single return value
  • multi return values
  • multi return values using ARRAY object
  • multi return values using JSON object

 

CLIENT SCRIPT

 

function onLoad() {
    //--uncomment just one of below to test

    //ajax1();
    //ajax2();
    //ajax3();
    ajax4();

}



function ajax1() {

    var ga = new GlideAjax('rds_testajax');
    ga.addParam('sysparm_name', 'getUserDetails_singleVal');
    ga.getXMLAnswer(function(answer) {
        alert('AJAX CALL 1');
        alert('AJAX SINGLE VAL return: ' + answer);

    });
}

function ajax2() {

    var ga2 = new GlideAjax('rds_testajax');
    ga2.addParam('sysparm_name', 'getUserDetails_multiVals');
    ga2.getXML(function(serverResponse) {
        var result = serverResponse.responseXML.getElementsByTagName("result");
        var message = result[0].getAttribute("message");
        //alert(message);
        //--get favorite elements
        var favorites = serverResponse.responseXML.getElementsByTagName("favorite");
        alert('AJAX CALL 2');
        for (var i = 0; i < favorites.length; i++) {
            var name = favorites[i].getAttribute("name");
            var value = favorites[i].getAttribute("value");
            alert(name + ': ' + value);
        }

    });
}


function ajax3() {

    var ga3 = new GlideAjax('rds_testajax');
    ga3.addParam('sysparm_name', 'getUserDetails_array');
    ga3.getXML(function processdata(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer");

        if (answer) {
            alert('AJAX CALL 3');
            answer = JSON.parse(answer);
            alert('EMAIL: ' + answer.email);
            alert('DEPT: ' + answer.displayDepartment);
            alert('NAME: ' + answer.name);
        }
    });
}

function ajax4() {

    var ga3 = new GlideAjax('rds_testajax');
    ga3.addParam('sysparm_name', 'getUserDetails_JSONobj');
    ga3.getXML(function processdata(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer");

        if (answer) {
            alert('AJAX CALL 4');
            var json_res = JSON.parse(answer);
            alert('EMAIL: ' + json_res.email);
            alert('NAME: ' + json_res.name);
        }
    });
}

 

SCRIPT INCLUDE (client=true) 

var rds_testajax = Class.create();
rds_testajax.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    getUserDetails_singleVal: function() {
        var returnVal = '';
        var caller = gs.getUserID();
        var returnUserObj = {}; // Declaring an object
        var userRec = new GlideRecord('sys_user');
        userRec.addQuery('sys_id', caller);
        userRec.query();
        //Record found
        if (userRec.next()) {
            returnVal = userRec.getValue('email');
        }
        return returnVal;
    },

    getUserDetails_multiVals: function() {
        var result = this.newItem("result");
        result.setAttribute("message", "returning all favorites");
        var caller = gs.getUserID();
        var returnUserObj = {}; // Declaring an object
        var userRec = new GlideRecord('sys_user');
        userRec.addQuery('sys_id', caller);
        userRec.query();
        //Record found
        if (userRec.next()) {

            this._addFavorite('email', userRec.getValue('email'));
            this._addFavorite('name', userRec.getValue('name'));
            this._addFavorite('first_name', userRec.getValue('first_name'));
            this._addFavorite('last_name', userRec.getValue('last_name'));
        }
        return result;
    },

    _addFavorite: function(name, value) {
        var favs = this.newItem("favorite");
        favs.setAttribute("name", name);
        favs.setAttribute("value", value);
    },


    getUserDetails_array: function() {

        var caller = gs.getUserID();
        var returnUserObj = {}; // Declaring an object
        var userRec = new GlideRecord('sys_user');
        userRec.addQuery('sys_id', caller);
        userRec.query();
        //Record found
        if (userRec.next()) {
            //name
            returnUserObj.name = userRec.getValue('name');
            returnUserObj.firstName = userRec.getValue('first_name');
            returnUserObj.lastName = userRec.getValue('last_name');

            //email
            returnUserObj.email = userRec.getValue('email'); // Adding properties
            returnUserObj.displayEmail = userRec.getDisplayValue('email');

            //phone
            returnUserObj.phone = userRec.getValue('phone'); // Adding properties
            returnUserObj.displayPhone = userRec.getDisplayValue('phone');

            //Department
            returnUserObj.department = userRec.getValue('department');
            returnUserObj.displayDepartment = userRec.getDisplayValue('department');

            //Cost Center
            returnUserObj.costCenter = userRec.getValue('cost_center');
            returnUserObj.displayCostCenter = userRec.getDisplayValue('cost_center');


            //Manager
            returnUserObj.manager = userRec.getValue('manager');
            returnUserObj.displayManager = userRec.getDisplayValue('manager');

            //Location
            returnUserObj.location = userRec.getValue('location');
            returnUserObj.displayLocation = userRec.getDisplayValue('location');

            //VIP Flag
            returnUserObj.vip = userRec.getValue('vip');



            return (JSON.stringify(returnUserObj));

        } else
            return;

    },

    getUserDetails_JSONobj: function() {

        var oResult = {
            "email": "",
            "name": ""
        };
        var caller = gs.getUserID();
        var returnUserObj = {}; // Declaring an object
        var userRec = new GlideRecord('sys_user');
        userRec.addQuery('sys_id', caller);
        userRec.query();
        //Record found
        if (userRec.next()) {
            oResult.email = userRec.getValue("email");
            oResult.name = userRec.getValue("name");
        }
        return (JSON.stringify(oResult));
    },

    type: 'rds_testajax'
});

Comments

Popular posts from this blog

ServiceNow check for null or nil or empty (or not)

Haven't tested these all recently within global/local scopes, so feel free to have a play! option 1 use an encoded query embedded in the GlideRecord , e.g.  var grProf = new GlideRecord ( 'x_cls_clear_skye_i_profile' ); grProf . addQuery ( 'status=1^ owner=NULL ' ); grProf . query (); even better use the glideRecord  addNotNullQuery or addNullQuery option 2 JSUtil.nil / notNil (this might be the most powerful. See this link ) example: if ( current . operation () == 'insert' && JSUtil . notNil ( current . parent ) && ! current . work_effort . nil ())  option 3 there might be times when you need to get inside the GlideRecord and perform the check there, for example if the code goes down 2 optional routes depending on null / not null can use gs.nil : var grAppr = new GlideRecord ( 'sysapproval_approver' ); var grUser = new GlideRecord ( 'sys_user' ); if ( grUser . get ( 'sys_id' , current . approver )){...

Code a pause/wait - gs.sleep or gs.wait alternative, pause script for specified seconds (timer)

Code a pause/wait - gs.sleep / gs.wait alternative, pause script for specified seconds (timer)  e.g. 10 seconds: do_sleep ( 10000 ); function do_sleep ( milliseconds ) { var start = new Date (). getTime (); for ( var i = 0 ; i < 1e7 ; i ++) { if (( new Date (). getTime () - start ) > milliseconds ){ gs . print ( 'waking up!' ); break ; } } }