Populating a Drop-down with an API/ Script Include

appstorm
Tera Contributor

I'm new to API's in ServiceNow and wondering how I can dynamically populate a list of courses in a drop-down, using an onChange Client Script and a Script Include to call a REST message.  Below, is my CS and SI.  I keep getting Java console errors on page load and not sure where the problem may lie.

 

var Test = Class.create();

Test.prototype = Object.extendsObject(AbstractAjaxProcessor, {

 CourseUtils: function()

   {

   try {

   var r = new sn_ws.RESTMessageV2('Courses', 'get');

   var response = r.execute();

   var responseBody = response.getBody();

   var httpStatus = response.getStatusCode();

   return responseBody;

   }

   catch(ex) {

   var message = ex.getMessage();

   return "";

   }

   },

       type: 'Test'

});

 

CS

function onLoad() {

     //Type appropriate comment here, and begin script below

var ga = new GlideAjax('Test');

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

ga.getXML(getCoursesOutput);

} 

function getCoursesOutput(response) {

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

   alert(answer);

     var objJSON = JSON.parse(answer);

   for(var loop = 0 ; loop < objJSON.courses.length;loop++)

   {

   alert(objJSON.courses[loop].Name);

   g_form.addOption('u_course_information',objJSON.courses[loop].Value,objJSON.courses[loop].Name);

   }

}

 

I know there needs to be something in the SI that matches output from my REST.  I'm not sure where to put that.

4 REPLIES 4

appstorm
Tera Contributor

I found this from another post:

return '{\"categories\":[{\"Name":\"John\", \"Value\":\"Doe\"}, {\"Name":\"Anna\", \"Value\":\"Smith\"},{\"Name":\"Peter\", \"Value\":\"Jones\"}]}';

 

...Would need to replace with the output from my REST?


{"detail":[{"loc":["query","term_code"],"msg":"field required","type":"value_error.missing"}]}

Sandeep Rajput
Tera Patron
Tera Patron

@appstorm Do you get the alert 

 alert(answer);

when this script runs on Load?

 

Also, could you please post your sample response.

I made some changes to both the SI and CS and get a response.  Question is now how do I return a JSON string in the drop-down?

@appstorm 

 

function onLoad() {

    var ga = new GlideAjax('Test');

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

    ga.getXML(getCoursesOutput);

}

 

function getCoursesOutput(response) {

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

    

  

    var objJSON;

    try {

        objJSON = JSON.parse(answer);

    } catch (e) {

        alert("Error in JSON: " + e);

        return;

    }

    for (var loop = 0; loop < objJSON.courses.length; loop++) {

alert( objJSON.courses[loop]);

        g_form.addOption('u_course_information', objJSON.courses[loop].Value, objJSON.courses[loop].Name);

    }

 

 

What are getting in response..can you share it 

 

Is it a obj with key value ?

}