This article is a supplement to the ServiceNow documentation. For full documentation please refer ServiceNow official website
Checkout our NEW Video Channel you can like and subscribe too!

Introduction

This is a continuation of our previous script include post. In this post we will deep dive and see more indept examples of handling GlideAjax API. We will go through examples starting from simple string to list of custom Json object.

Json Way

GlideAjax returns as a xml object. By nature xml have a hierarchy and attributes and tags. When we use an answer object, the answer is wrapped and send as an attribute back to browser

script-include.jpg

In Browser Console

xml-answer.JPG

So to retrieve in client script we have to use like below response.responseXML.documentElement.getAttribute(‘answer’);

XML Way

If a pure XML is returned then

In Browser Console

pure-xmk-browser.JPG

Server Side

To send pure xml element , we have to send values as attributes like below

  var answer = this.newItem("learnnowlab");
  answer.setAttribute("result", "OK");
  answer.setAttribute("argument", "param");
  return; // no argument is required for return

Client Side

To retrieve at client script we have to get it by tag element

var answer = response.responseXML.getElementsByTagName("learnnowlab");
console.log(answer[0].getAttribute("result"))

In short use json format as it much easier to write and retrieve in the client side. As the answer object can be virtually any JavaScript object we can pass a array list of JavaScript object too.

JSON encode and decode

Encoding converts javascript object to string , then it is send over the wires to client. client decodes and gets the java script object back

decode-encode.JPG

Ajax Examples

We tried to fit in all the examples in 1 client script and 1 script include so that we can use the same example.THis makes easy to understand things progressively

Client Side

function onLoad() {

    var randUser = Math.floor(Math.random() * 10);
    var getUserList = new GlideAjax("getUserDetails");
    getUserList.addParam('sysparm_name', 'getRandomUsers');
    getUserList.addParam('sysparm_random', randUser);

    //Option1: Get the whole XML
    //getUserList.getXML(callback);

    //Option 2: Get Answer Object
    //getUserList.getXMLAnswer(callback);

    //Option 3: Pure xml
    getUserList.getXML(callback);

}

function callback(response) {

    //Use this if option1 is used above
    //var answer = response.responseXML.documentElement.getAttribute('answer');
    //console.log(response.responseXML.documentElement);

    //for string answers
    //answer = answer;

    //for stringfied Json object
    //answer = JSON.parse(answer);
    //console.log(answer.name)

    //for Json Object	
    // answer = JSON.parse(answer);
    // console.log(answer.result);

    //for Json Array

    //Use this if option1 is used above
    /*answer = JSON.parse(answer);
    for (i = 0; i < answer.length; i++) {
        console.log(answer[i].userName);
    }
	*/

    //Use this if option2 is used above
    /*var answer = JSON.parse(response);
    for (i = 0; i < answer.length; i++) {
        console.log(answer[i].userName);
    }*/

    //Use this if option3 is used above
    var answer = response.responseXML.getElementsByTagName("learnnowlab");
    //console.log(response.responseXML.getElementsByTagName("learnnowlab"));
    //console.log(answer[0].getAttribute("result"));

}

server side

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

    getRandomUsers: function() {

        /*
		Json Array with GlideRecord
		===============================
		*/

        /*
        var pickUsers = this.getParameter('sysparm_random');
        var responseObject = {};
        var resArray = [];

        var usr = new GlideRecord('sys_user');
        usr.setLimit(pickUsers);
        usr.query();

        while (usr.next()) {
            responseObject = {};
            responseObject.userName = usr.user_name.toString();
            resArray.push(responseObject);
        }
        return new JSON().encode(resArray);
		*/


        /*
		Only String
		==============================
		*/

        //return "test";

        /*
		Stringyfied Json
		==============================
		*/

        //return "{\"name\":\"john\",\"age\":22,\"class\":\"mca\"}";

        /*
		Json Object
		==============================
		*/

        /*
        var jsonData = {
            "result": "OK",
            "argument": "param",
        };
        //Stringfied Json Object
        return new JSON().encode(jsonData);
       */

        /*Pure XML
        ================================
		*/
        var answer = this.newItem("learnnowlab");
        answer.setAttribute("result", "OK");
        answer.setAttribute("argument", "param");
        return; // no argument is required for return

    },

    type: 'getUserDetails'
});
    Content