Form Drop-Down Displays No Data from Server onLoad

appstorm
Tera Contributor

Trying to populate a form drop-down on portal, using a catalog client script/ script include to return JSON from an internal REST message.  However, I can't get it to display on form load.

 

REST Config:

appstorm_4-1741300194987.png

 

SI:

appstorm_1-1741299845741.png

var LARFBannerCoursesEndpoint = Class.create();
LARFBannerCoursesEndpoint.prototype = Object.create(global.AbstractAjaxProcessor.prototype);
LARFBannerCoursesEndpoint.prototype.process = function() {
    var restEndpoint = 'LARF Banner Courses';
    gs.log('Rest endpoint:', restEndpoint);
    
    var response = new sn_ws.RESTMessageV2().setEndpoint(restEndpoint).setHttpMethod('GET').execute();
    gs.log('Response:', response);
    
    if (response !== null) {
        var responseBody = response.getBody();
        gs.log('Response body:', responseBody);
        
        try {
            var courses = JSON.parse(responseBody);
            gs.log('Parsed response:', courses);
            
            return courses;
        } catch (error) {
            gs.log('Error parsing response:', error);
            return [];
        }
    } else {
        gs.log('No response from server');
        return [];
    }
};

 

CS:

appstorm_2-1741299965653.png

function onLoad() {
    var ga = new GlideAjax('LARFBannerCoursesEndpoint');
    ga.addParam('sysparm_name', 'process');
    ga.getXMLAnswer(function(answer) {
        if (answer) {
            var courses = JSON.parse(answer);
            
            g_form.clearOptions('course_information');
            
            for (var i = 0; i < courses.length; i++) {
                var course = courses[i];
                g_form.addOption('course_information', course.label, course.value);
            }
        } else {
            g_form.showErrorBox('course_information', 'Error: no data returned from server');
        }
    });
}

 

Form onLoad:

appstorm_3-1741300040947.png

 

1 REPLY 1

Medi C
Giga Sage

Hi @appstorm

Using GlideAjax to populate a field in ServiceNow is not a good practice because GlideAjax is asynchronous. This means that when you call it, the script execution does not wait for the server to return a response before continuing. As a result, by the time the response arrives, the script that needed the value may have already executed without it, leading to unexpected behavior.

If the courses are not changing every minute, what I would recommend is to have a dedicated table for them (Check if your licenses allow you to create custom tables). Then have a scheduled job running on daily/weekly frequency to make the rest call and create/deactivate course records on your custom table.

 

Then your field would simply reference this custom table. 


If you found this helpful, please hit the thumbs-up button and mark as correct. That helps others find their solutions.