Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

how to parse json string and display it in ui page

suprakash
Giga Expert

I need to display the first five created asset names and asset category according to their creation date in a Ui page in table format . i have written script include

--script include ---

var getAssetClass = Class.create();

getAssetClass.prototype = Object.extendsObject(AbstractAjaxProcessor, {

  getAsset: function() {

  var gr = new GlideRecord('alm_asset');

  gr.orderBy('sys_created_on');

  gr.setLimit(5);

  gr.query();

  var assets=[];

  while(gr.next()){

      asset={};

      var asset_name = gr.getDisplayValue('display_name');

      asset.name=asset_name;

      asset.category=gr.getDisplayValue('model_category');

      assets.push(asset);

 

      //gs.print(asset.name+"!!!!!!!!!!"+asset.category);

  }

  //gs.print(assets);

  var assetsString = JSON.stringify(assets);

        return assetsString;

    },

  //getDisplay: function() {

  // return 10;

  //},

      type: "getAssetClass"

});

-- client script for testing---------

var ga = new GlideAjax('getAssetClass');

  ga.addParam('sysparm_name','getAsset');

  //ga.addParam('sysparm_name1','getDisplay');

  //ga.addParam('sysparm_user_name',"Bob");

  ga.getXML(HelloFun);

  function HelloFun(response) {

  var answer = response.responseXML.documentElement.getAttribute("answer");

  //console.log(answer);

  alert(answer);

  }

i am not able to parse the JSON string and display it in ui page in table format using HTML

6 REPLIES 6

Harsh Vardhan
Giga Patron

Hi Suprakash,



In UI Page you need to mention your code under "g:evaluate" tag then store it in a variable and call it in client script.



Please find the below example   : It's the OOTB ui page " approval_engines ".


Please check the below code.



HTML Script



<g:ui_form>


    <g:evaluate var="jvar_engines">


          function getWorkflowManagedTables() {


                  // sys_ids of the approval activities (wf_activity_definition)


                  var approvalActivities = getApprovalActivityDefinitionIds();


                  var arrayUtil = new ArrayUtil();


                  var workflowTables = [];


                  var grV = new GlideRecord('wf_workflow_version');


                  grV.addQuery('published', true);


                  grV.query();


                  while (grV.next()) {


                          if (arrayUtil.contains(workflowTables, grV.table + ''))


                                  continue;


                          grA = new GlideRecord('wf_activity');


                          grA.addQuery('workflow_version', grV.getUniqueValue());


                          grA.addQuery('activity_definition', 'IN', approvalActivities);


                          grA.query();


                          if (grA.next())


                                  workflowTables.push(grV.table + '');


                  }


                  return workflowTables;


                 


                  function getApprovalActivityDefinitionIds() {


                          var approvalActivityIds = '';


                          var gr = new GlideRecord('wf_activity_definition');


                          gr.addQuery('attributes', 'CONTAINS', 'approval');


                          gr.query();


                          while (gr.next()) {


                                  var att = GlideStringUtil.decodeAttributes(gr.attributes + '');


                                  if (att.get('approval') + '' == 'true') {


                                          if (approvalActivityIds.length > 0)


                                                  approvalActivityIds += ',';


                                          approvalActivityIds += gr.sys_id + '';


                                  }


                          }


                          return approvalActivityIds;


                  }


          }


          var workflowTables = getWorkflowManagedTables();


          var tables = new GlideDBObjectManager.get().getAllExtensions('task');


          var tableList = [];


          for (var i = 0; i != tables.size(); i++) {


                tableList.push(tables.get(i) + '');


          }


          tableList.sort();


          var engines = [];


          for (var i = 0; i != tableList.length; i++) {


                var engine = {};


                engine.table = tableList[i];


                var td = new GlideTableDescriptor.get(engine.table);


                engine.label = td.getLabel() + '';


                engine.approval = new ApprovalEngineUtils().getEngineForTable(engine.table);


                var notesKey = "approval_engine.notes." + engine.table;


                var notes = gs.getMessage(notesKey) + '';


                if (notes == notesKey)


                      notes = '';


                     


                engine.notes = notes;




                if (new ArrayUtil().contains(workflowTables, engine.table)) {


                      var additionalNotes = gs.getMessage('Workflows are managing approvals on this table.') ;


                      if (engine.approval == 'off')


                            engine.disable = true;


                      else


                            additionalNotes += ' ' + gs.getMessage('This should be set to "Turn Engines Off".');


                           


                      if (engine.notes == '')


                              engine.notes = additionalNotes;


                }




                engines.push(engine);


          }


          var json = new JSON();


          json.encode(engines);


    </g:evaluate>


   


    <table border="0" cellspacing="0" cellpadding="0">


          <tr>


                <g:no_escape>


                      <td colspan="5">${gs.getMessage("approval_engine.description")}</td>


                </g:no_escape>


          </tr>


    </table>




    <table border="0" cellspacing="2" cellpadding="0" id="engines">


          <tr class="header">


                <td nowrap="true" class="column_head" align="center">${gs.getMessage("Table")}</td>


                <td nowrap="true" class="column_head" align="center">${gs.getMessage("Name")}</td>


                <td nowrap="true" class="column_head" align="center">${gs.getMessage("Approval Engine")}</td>


                <td class="column_head" align="center">


                      ${gs.getMessage("Notes")}


        <input id="make_spacing_ok" style="visibility:hidden;width:0px;" title=""/>


                </td>


          </tr>


    </table>


    <input type="hidden" id="tables" name="tables" />


    <script>


          var g_engines = ${jvar_engines};


    </script>


   


    <g:dialog_button onclick="save()" style="" id="engine_save" type="submit">${gs.getMessage("Save")}</g:dialog_button>


</g:ui_form>




Client script




var t = gel("engines");


var tbody = t.firstChild;




initEngines();




function initEngines() {


    var tables = [];


    for (var i = 0; i < g_engines.length; i++) {


          buildEngineTR(g_engines[i], i);


          tables.push(g_engines[i].table);


    }


    var e = gel("tables");


    e.value = tables.join(",");


}




function buildEngineTR(engine, i) {


    var tr = cel("tr", tbody);


    if ((i % 2) == 0)


          tr.className = "even";


    else


          tr.className = "odd";


         


    var hasEngine = false;


    if (engine.approval)


          hasEngine = true;


         


    var td = cel("td", tr);


    td.className = "vt";


    td.style.whiteSpace = "nowrap";


    if (hasEngine)


          td.innerHTML = "<b>" + engine.label + "</b>";


    else


          td.innerHTML = engine.label;


   


    td = cel("td", tr);


    td.className = "vt";


    td.style.whiteSpace = "nowrap";


    if (hasEngine)


          td.innerHTML = "<b>" + engine.table + "</b>";


    else


          td.innerHTML = engine.table;


   


    td = cel("td", tr);


    td.className = "vt";


    buildEngineSelect(td, engine);


    td = cel("td", tr);


    td.className = "vt";


    td.innerHTML = engine.notes;


}




function buildEngineSelect(td, engine) {


    var select = cel("select", td);


    select.className = "vt";


    select.id = "engine_" + engine.table;


    select.name = select.id;


    select.title = "Approval Engine";


    if (engine.disable)


          select.disabled = "disabled";


    addOption(select, "approval_engine", "Approval Rules", engine.approval == "approval_engine");


    addOption(select, "process_guide", "Process Guides", engine.approval == "process_guide");


    addOption(select, "off", "Turn engines off", engine.approval == "off");


}




function save() {


}




Hope it will help you.Let me know if you need any further information.



Thanks,


Harshvardhan



PS: Hit like, Helpful or Correct depending on the impact of the response.


Shamma Negi
Kilo Sage
Kilo Sage

Hi Suprakash,



See the below code:



HTML :



<?xml version="1.0" encoding="utf-8" ?>


<j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">




<g2:evaluate var="jvar_gr2" object="true">


var crrSysID = "${RP.getWindowProperties().get('sysparm_crr_sysid')}";


    </g2:evaluate>



<g:ui_form>


  <input type="hidden" value="$[crrSysID]" name="crrSysId" id="crrSysId" />


</g:ui_form>



How to use this in CLIENT SCRIPT :



var crrSysId= $('crrSysID').getValue();



This way you can create variable in HTML and use it in Client script.



Let me know in case of any questions.



PS: Hit like, Helpful or Correct depending on the impact of the response.



Regards,


Shamma


Regards,Shamma Negi