One thing that I’ve seen more than a few people struggle with is how to get data from the Server to the client when using Jelly in UI Pages and UI Macros. As such I wanted to give some examples today which would help. The “secret” is that you can use the same “Server-side” (Jelly) variables inside the Client script section (on UI pages) or within “script” tags on UI Macros.

So as in our examples below, let’s say that you had a Jelly variable called “serverArr” which you declare within the “g:evaluate” tags which gets processed on the Server-side. The evaluate code loops through a table and builds a collection of JSON objects which get added to this array variable. To use this object we need to first encode it into JSON on the server, then we can simply use the same variable name within the corresponding client script section of “${serverArr}” (without double quotes), and when ServiceNow goes to build the Page/Macro it will substitute the variable in the client script with our data from the server.

UI Page



    
        
        var serverArr = [];
        var gr = new GlideRecord('incident');
        gr.setLimit(5);
        gr.query();
        while (gr.next()) {
        var obj = {}
        obj.number = gr.number.toString()
        obj.short_desc = gr.short_description.toString();
        serverArr.push(obj);
        }

        serverArr = new global.JSON().encode(serverArr);
        serverArr; 
       

Working with the following “Server data” on the Client side:

Client Script Section of UI Page: Note that this must be pasted into this section via the list view of the page otherwise it will complain about the use of the ${serverArr} variable.

   var objArr = ${serverArr};
   jQuery('body').append(JSON.stringify(objArr) + '');
   for (var i= 0; i < objArr.length; i++) {
        var obj = objArr[i];
        jQuery('body').append(obj.number + ' - ' + obj.short_desc + '');
   }

Server Data - UI Page 1

UI Macro


    var serverArr = [];
    var gr = new GlideRecord('incident');
    gr.setLimit(5);
    gr.query();
    while (gr.next()) {
    var obj = {}
    obj.number = gr.number.toString()
    obj.short_desc = gr.short_description.toString();
    serverArr.push(obj);
    }

    serverArr = new global.JSON().encode(serverArr);
    serverArr;
 
//

Note that the above script sections do not have a "/" I just needed to do that as WordPress kept trying to render them as in-line scripts!
Server Data - UI Macro