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.

UI Action not calling script include.

CandyDee
Kilo Sage

Morning All, 

 

Hoping one of the community peeps may spot why my UI action isn't calling the script include. I cant see why myself and hoping a fresh pair of eyes may spot something I'm missing, this isn't the final script include or UI action just trying to test through from the UI down to Server Level.

 

Ive removed sensitive data. 

 

Apologies for all the console logs and logging as trying to figure out whats going on. 

 

Script include and UI action are client callable. If I run a background script against the script include it works perfectly.

 

The ui action is retrieving the correct values for the serverdetailshelper script include and the accountdetailshelper script include, I can see on the console.log 'calling GetServices1' with the correct data, the next console log shows 'received response from getservices1 'null',.

 

I added logs at the top of the script include to see if it had been called but this doesnt show in the logs so it doesnt look like the script include is being called at all. 

 

ui action

 

function ServiceDiscovery() {
    var serverSysId = g_form.getValue('server');
    var accountSysId = g_form.getValue('account');

    console.log('Calling ServerDetailsHelper with serverSysId:', serverSysId);
    console.log('Calling AccountDetailsHelper with accountSysId:', accountSysId);

    var gaServer = new GlideAjax('ServerDetailsHelper');
    gaServer.addParam('sysparm_name', 'getServerDetails');
    gaServer.addParam('sysparm_serverSysId', serverSysId);

    gaServer.getXMLAnswer(function(responseServer) {
        console.log('Received response from ServerDetailsHelper:', responseServer);

        if (responseServer) {
            try {
                var answerServer = JSON.parse(responseServer);
                console.log('Parsed server details:', answerServer);

                if (answerServer && answerServer.success) {
                    var serverURN = answerServer.serverURN;
                    console.log('serverURN:', serverURN);

                    var gaAccount = new GlideAjax('AccountDetailsHelper');
                    gaAccount.addParam('sysparm_name', 'getAccountDetails');
                    gaAccount.addParam('sysparm_accountSysId', accountSysId);

                    gaAccount.getXMLAnswer(function(responseAccount) {
                        console.log('Received response from AccountDetailsHelper:', responseAccount);

                        if (responseAccount) {
                            try {
                                var answerAccount = JSON.parse(responseAccount);
                                console.log('Parsed account details:', answerAccount);

                                if (answerAccount && answerAccount.success) {
                                    var accountDomainId = answerAccount.accountDomainId;
                                    console.log('accountDomainId:', accountDomainId);

                                    var gaServices = new GlideAjax('GetServices1');
                                    gaServices.addParam('sysparm_name', 'getServices1');
                                    gaServices.addParam('sysparm_serverSysId', serverURN);
                                    gaServices.addParam('sysparm_accountSysId', accountDomainId);

                                    console.log('Calling GetServices1 with serverURN:', serverURN, 'and accountDomainId:', accountDomainId);

                                    gaServices.getXMLAnswer(function(responseServices) {
                                        console.log('Received response from GetServices1:', responseServices);

                                        if (responseServices) {
                                            try {
                                                var answerServices = JSON.parse(responseServices);
                                                console.log('Parsed result:', answerServices);

                                                if (answerServices && !answerServices.error) {
                                                    console.log('Services retrieved successfully. Check logs for details.');
                                                } else {
                                                    console.error('Failed to retrieve services:', answerServices.error || 'Unknown error');
                                                }
                                            } catch (e) {
                                                console.error('Error parsing response from GetServices1:', e);
                                            }
                                        } else {
                                            console.error('Invalid response from GetServices1:', responseServices);
                                        }
                                    });
                                } else {
                                    console.error('Failed to retrieve account details:', answerAccount.message || 'Unknown error');
                                }
                            } catch (e) {
                                console.error('Error parsing response from AccountDetailsHelper:', e);
                            }
                        } else {
                            console.error('Invalid response from AccountDetailsHelper:', responseAccount);
                        }
                    });
                } else {
                    console.error('Failed to retrieve server details:', answerServer.message || 'Unknown error');
                }
            } catch (e) {
                console.error('Error parsing response from ServerDetailsHelper:', e);
            }
        } else {
            console.error('Invalid response from ServerDetailsHelper:', responseServer);
        }
    });
}

Script include- 

 

var GetServices1 = Class.create();
GetServices1.prototype = {
    initialize: function() {},

    getServices1: function() {
        var serverSysId = this.getParameter('sysparm_serverSysId');
        var accountSysId = this.getParameter('sysparm_accountSysId');

        gs.info('GetServices1 called with parameters: serverSysId=' + serverSysId + ', accountSysId=' + accountSysId);

        if (!serverSysId || !accountSysId) {
            gs.error('GetServices1 missing required parameters: serverSysId or accountSysId.');
            return JSON.stringify({
                error: 'Missing required parameters.'
            });
        }

        gs.info('GetServices1 parameters received correctly. Calling getServices function.');
        return this.getServices(serverSysId, accountSysId);
    },

    getServices: function(serverSysId, accountSysId) {
        gs.info('getServices function started with serverSysId=' + serverSysId + ', accountSysId=' + accountSysId);

        var tokenDetails = this.getIdentityToken();
        var tokenId = tokenDetails ? tokenDetails.id : null;

        if (tokenId) {
            gs.info('Token ID: ' + tokenId);

            var servicesPostResult = this.servicesPost(accountSysId, tokenId, serverSysId);
            gs.info('Services Post Result: ' + JSON.stringify(servicesPostResult));

            if (servicesPostResult && servicesPostResult.bookmark) {
                var bookmark = servicesPostResult.bookmark;
                var servicesGetResult = this.servicesGet(accountSysId, tokenId, bookmark);
                gs.info('Services Get Result: ' + JSON.stringify(servicesGetResult));

                return JSON.stringify({
                    serverSysId: serverSysId,
                    accountSysId: accountSysId,
                    tokenId: tokenId,
                    servicesPostResult: servicesPostResult,
                    servicesGetResult: servicesGetResult
                });
            } else {
                gs.error('Failed to retrieve the bookmark.');
                return JSON.stringify({
                    serverSysId: serverSysId,
                    accountSysId: accountSysId,
                    tokenId: tokenId,
                    error: 'Failed to retrieve the bookmark.'
                });
            }
        } else {
            gs.error('Failed to retrieve the token ID.');
            return JSON.stringify({
                serverSysId: serverSysId,
                accountSysId: accountSysId,
                error: 'Failed to retrieve the token ID.'
            });
        }
    },

    getIdentityToken: function() {
        try {
            gs.info('getIdentityToken function started.');

            var request = new sn_ws.RESTMessageV2('');
            request.setRequestHeader('Accept', 'application/json');
            request.setRequestHeader('Content-Type', 'application/json');

            var requestBody = JSON.stringify({
                auth: {
                   
            });
            request.setRequestBody(requestBody);

            var response = request.execute();
            var responseBody = response.getBody();
            var httpStatus = response.getStatusCode();

            gs.info('getIdentityToken HTTP Status: ' + httpStatus);
            gs.info('getIdentityToken Response: ' + responseBody);

            if (httpStatus == 200) {
                var responseJson = JSON.parse(responseBody);
                return responseJson.access.token;
            } else {
                gs.error('Failed to get identity token. HTTP Status: ' + httpStatus);
                return null;
            }
        } catch (ex) {
            gs.error('Error while getting identity token: ' + ex.message);
            return null;
        }
    },

    servicesPost: function(accountSysId, tokenId, serverSysId) {
        try {
            gs.info('servicesPost function started with accountSysId=' + accountSysId + ', tokenId=' + tokenId + ', serverSysId=' + serverSysId);

            var endpoint = ';
            var request = new sn_ws.RESTMessageV2();
            request.setHttpMethod('POST');
            request.setEndpoint(endpoint);
            request.setRequestHeader('Content-Type', 'application/json');
            request.setRequestHeader('x-auth-token', tokenId);
            request.setRequestHeader('x-tenant-id', accountSysId);

            var requestBody = JSON.stringify({
               
            });
            request.setRequestBody(requestBody);

            var response = request.execute();
            var responseBody = response.getBody();
            var httpStatus = response.getStatusCode();

            gs.info('servicesPost HTTP Status: ' + httpStatus);
            gs.info('servicesPost Response: ' + responseBody);

            if (httpStatus == 200 || httpStatus == 201) {
                return JSON.parse(responseBody);
            } else {
                gs.error('Failed to post to services. HTTP Status: ' + httpStatus);
                return {
                    error: 'Failed to post to services. HTTP Status: ' + httpStatus
                };
            }
        } catch (ex) {
            gs.error('Error while posting to services: ' + ex.message);
            return {
                error: 'Error while posting to services: ' + ex.message
            };
        }
    },

    servicesGet: function(accountSysId, tokenId, bookmark) {
        gs.info('servicesGet function started with accountSysId=' + accountSysId + ', tokenId=' + tokenId + ', bookmark=' + bookmark);

        var endpoint = 
        var maxAttempts = 10;
        var attempt = 0;
        var delay = 60000;
        var responseJson = null;
        var state = '';

        try {
            while (attempt < maxAttempts && (state === '' || state === 'pending' || state === 'progress')) {
                attempt++;
                gs.info('servicesGet attempt ' + attempt + ' for endpoint ' + endpoint);

                var request = new sn_ws.RESTMessageV2();
                request.setHttpMethod('GET');
                request.setEndpoint(endpoint);
                request.setRequestHeader('Accept', 'application/json');
                request.setRequestHeader('x-auth-token', tokenId);
                request.setRequestHeader('x-tenant-id', accountSysId);

                var response = request.execute();
                var responseBody = response.getBody();
                var httpStatus = response.getStatusCode();

                gs.info('servicesGet HTTP Status: ' + httpStatus);
                gs.info('servicesGet Response: ' + responseBody);

                if (httpStatus == 200) {
                    responseJson = JSON.parse(responseBody);
                    state = responseJson.state;

                    if (state === 'pending' || state === 'progress') {
                        gs.info('State is ' + state + '. Waiting for ' + delay / 60000 + ' minutes before next attempt.');
                        gs.sleep(delay);
                    }
                } else {
                    gs.error('Failed to get services. HTTP Status: ' + httpStatus);
                    return {
                        error: 'Failed to get services. HTTP Status: ' + httpStatus
                    };
                }
            }

            if (state !== 'pending' && state !== 'progress') {
                gs.info('Final Services Get Response: ' + JSON.stringify(responseJson));
                if (responseJson && responseJson.result && responseJson.result.length > 0) {
                    var services = responseJson.result[0].result[0].services;
                    for (var i = 0; i < services.length; i++) {
                        var service = services[i];
                       // gs.info('Service Name: ' + service.name + ', State: ' + service.state);
                    }
                }
                return responseJson;
            } else {
                return {
                    error: 'Max attempts reached without a final state.'
                };
            }
        } catch (ex) {
            gs.error('Error while getting services: ' + ex.message);
            return {
                error: 'Error while getting services: ' + ex.message
            };
        }
    },

    type: 'GetServices1'
};

 

 

4 REPLIES 4

Mark Manders
Mega Patron

Can you try this UI action:

function ServiceDiscovery() {
    var serverSysId = g_form.getValue('server');
    var accountSysId = g_form.getValue('account');

    // Ensure gs.info() for server-side logging
    gs.info('Calling ServerDetailsHelper with serverSysId: ' + serverSysId);
    gs.info('Calling AccountDetailsHelper with accountSysId: ' + accountSysId);

    var gaServer = new GlideAjax('ServerDetailsHelper');
    gaServer.addParam('sysparm_name', 'getServerDetails');
    gaServer.addParam('sysparm_serverSysId', serverSysId);

    gaServer.getXMLAnswer(function(responseServer) {
        gs.info('Received response from ServerDetailsHelper: ' + responseServer);

        if (responseServer) {
            try {
                var answerServer = JSON.parse(responseServer);
                gs.info('Parsed server details: ' + JSON.stringify(answerServer));

                if (answerServer && answerServer.success) {
                    var serverURN = answerServer.serverURN;
                    gs.info('serverURN: ' + serverURN);

                    var gaAccount = new GlideAjax('AccountDetailsHelper');
                    gaAccount.addParam('sysparm_name', 'getAccountDetails');
                    gaAccount.addParam('sysparm_accountSysId', accountSysId);

                    gaAccount.getXMLAnswer(function(responseAccount) {
                        gs.info('Received response from AccountDetailsHelper: ' + responseAccount);

                        if (responseAccount) {
                            try {
                                var answerAccount = JSON.parse(responseAccount);
                                gs.info('Parsed account details: ' + JSON.stringify(answerAccount));

                                if (answerAccount && answerAccount.success) {
                                    var accountDomainId = answerAccount.accountDomainId;
                                    gs.info('accountDomainId: ' + accountDomainId);

                                    var gaServices = new GlideAjax('GetServices1');
                                    gaServices.addParam('sysparm_name', 'getServices1');
                                    gaServices.addParam('sysparm_serverSysId', serverURN);
                                    gaServices.addParam('sysparm_accountSysId', accountDomainId);

                                    gs.info('Calling GetServices1 with serverURN: ' + serverURN + ' and accountDomainId: ' + accountDomainId);

                                    gaServices.getXMLAnswer(function(responseServices) {
                                        gs.info('Received response from GetServices1: ' + responseServices);

                                        if (responseServices) {
                                            try {
                                                var answerServices = JSON.parse(responseServices);
                                                gs.info('Parsed result: ' + JSON.stringify(answerServices));

                                                if (answerServices && !answerServices.error) {
                                                    gs.info('Services retrieved successfully. Check logs for details.');
                                                } else {
                                                    gs.error('Failed to retrieve services: ' + (answerServices.error || 'Unknown error'));
                                                }
                                            } catch (e) {
                                                gs.error('Error parsing response from GetServices1: ' + e);
                                            }
                                        } else {
                                            gs.error('Invalid response from GetServices1: ' + responseServices);
                                        }
                                    });
                                } else {
                                    gs.error('Failed to retrieve account details: ' + (answerAccount.message || 'Unknown error'));
                                }
                            } catch (e) {
                                gs.error('Error parsing response from AccountDetailsHelper: ' + e);
                            }
                        } else {
                            gs.error('Invalid response from AccountDetailsHelper: ' + responseAccount);
                        }
                    });
                } else {
                    gs.error('Failed to retrieve server details: ' + (answerServer.message || 'Unknown error'));
                }
            } catch (e) {
                gs.error('Error parsing response from ServerDetailsHelper: ' + e);
            }
        } else {
            gs.error('Invalid response from ServerDetailsHelper: ' + responseServer);
        }
    });
}

 on this script include:

var GetServices1 = Class.create();
GetServices1.prototype = {
    initialize: function() {},
    
    getServices1: function() {
        var serverSysId = this.getParameter('sysparm_serverSysId');
        var accountSysId = this.getParameter('sysparm_accountSysId');
        
        gs.info('GetServices1 called with parameters: serverSysId=' + serverSysId + ', accountSysId=' + accountSysId);

        if (!serverSysId || !accountSysId) {
            gs.error('GetServices1 missing required parameters: serverSysId or accountSysId.');
            return JSON.stringify({
                error: 'Missing required parameters.'
            });
        }

        gs.info('GetServices1 parameters received correctly. Calling getServices function.');
        return this.getServices(serverSysId, accountSysId);
    },

    getServices: function(serverSysId, accountSysId) {
        gs.info('getServices function started with serverSysId=' + serverSysId + ', accountSysId=' + accountSysId);

        var tokenDetails = this.getIdentityToken();
        var tokenId = tokenDetails ? tokenDetails.id : null;

        if (tokenId) {
            gs.info('Token ID: ' + tokenId);

            var servicesPostResult = this.servicesPost(accountSysId, tokenId, serverSysId);
            gs.info('Services Post Result: ' + JSON.stringify(servicesPostResult));

            if (servicesPostResult && servicesPostResult.bookmark) {
                var bookmark = servicesPostResult.bookmark;
                var servicesGetResult = this.servicesGet(accountSysId, tokenId, bookmark);
                gs.info('Services Get Result: ' + JSON.stringify(servicesGetResult));

                return JSON.stringify({
                    serverSysId: serverSysId,
                    accountSysId: accountSysId,
                    tokenId: tokenId,
                    servicesPostResult: servicesPostResult,
                    servicesGetResult: servicesGetResult
                });
            } else {
                gs.error('Failed to retrieve the bookmark.');
                return JSON.stringify({
                    serverSysId: serverSysId,
                    accountSysId: accountSysId,
                    tokenId: tokenId,
                    error: 'Failed to retrieve the bookmark.'
                });
            }
        } else {
            gs.error('Failed to retrieve the token ID.');
            return JSON.stringify({
                serverSysId: serverSysId,
                accountSysId: accountSysId,
                error: 'Failed to retrieve the token ID.'
            });
        }
    },

    getIdentityToken: function() {
        try {
            gs.info('getIdentityToken function started.');

            var request = new sn_ws.RESTMessageV2('');
            request.setRequestHeader('Accept', 'application/json');
            request.setRequestHeader('Content-Type', 'application/json');

            var requestBody = JSON.stringify({
                auth: {
                    // Auth details here
                }
            });
            request.setRequestBody(requestBody);

            var response = request.execute();
            var responseBody = response.getBody();
            var httpStatus = response.getStatusCode();

            gs.info('getIdentityToken HTTP Status: ' + httpStatus);
            gs.info('getIdentityToken Response: ' + responseBody);

            if (httpStatus == 200) {
                var responseJson = JSON.parse(responseBody);
                return responseJson.access.token;
            } else {
                gs.error('Failed to get identity token. HTTP Status: ' + httpStatus);
                return null;
            }
        } catch (ex) {
            gs.error('Error while getting identity token: ' + ex.message);
            return null;
        }
    },

    servicesPost: function(accountSysId, tokenId, serverSysId) {
        try {
            gs.info('servicesPost function started with accountSysId=' + accountSysId + ', tokenId=' + tokenId + ', serverSysId=' + serverSysId);

            var endpoint = '';
            var request = new sn_ws.RESTMessageV2();
            request.setHttpMethod('POST');
            request.setEndpoint(endpoint);
            request.setRequestHeader('Content-Type', 'application/json');
            request.setRequestHeader('x-auth-token', tokenId);
            request.setRequestHeader('x-tenant-id', accountSysId);

            var requestBody = JSON.stringify({
                // Request body here
            });
            request.setRequestBody(requestBody);

            var response = request.execute();
            var responseBody = response.getBody();
            var httpStatus = response.getStatusCode();

            gs.info('servicesPost HTTP Status: ' + httpStatus);
            gs.info('servicesPost Response: ' + responseBody);

            if (httpStatus == 200 || httpStatus == 201) {
                return JSON.parse(responseBody);
            } else {
                gs.error('Failed to post to services. HTTP Status: ' + httpStatus);
                return {
                    error: 'Failed to post to services. HTTP Status: ' + httpStatus
                };
            }
        } catch (ex) {
            gs.error('Error while posting to services: ' + ex.message);
            return {
                error: 'Error while posting to services: ' + ex.message
            };
        }
    },

    servicesGet: function(accountSysId, tokenId, bookmark) {
        gs.info('servicesGet function started with accountSysId=' + accountSysId + ', tokenId=' +

Please mark any helpful or correct solutions as such. That helps others find their solutions.
Mark

Hi Mark, really appreciate the time youve taken to respond, on the last function servicesget it just shows as 

 servicesGet: function(accountSysId, tokenId, bookmark) {
        gs.info('servicesGet function started with accountSysId=' + accountSysId + ', tokenId=' +

Im checking thats the case and you didnt miss a few lines off. thanks

Yes, sorry... apparently not everything was copied, or it was cut off

servicesGet: function(accountSysId, tokenId, bookmark) {
        gs.info('servicesGet function started with accountSysId=' + accountSysId + ', tokenId=' + tokenId + ', bookmark=' + bookmark);

        var endpoint = 
        var maxAttempts = 10;
        var attempt = 0;
        var delay = 60000;
        var responseJson = null;
        var state = '';

        try {
            while (attempt < maxAttempts && (state === '' || state === 'pending' || state === 'progress')) {
                attempt++;
                gs.info('servicesGet attempt ' + attempt + ' for endpoint ' + endpoint);

                var request = new sn_ws.RESTMessageV2();
                request.setHttpMethod('GET');
                request.setEndpoint(endpoint);
                request.setRequestHeader('Accept', 'application/json');
                request.setRequestHeader('x-auth-token', tokenId);
                request.setRequestHeader('x-tenant-id', accountSysId);

                var response = request.execute();
                var responseBody = response.getBody();
                var httpStatus = response.getStatusCode();

                gs.info('servicesGet HTTP Status: ' + httpStatus);
                gs.info('servicesGet Response: ' + responseBody);

                if (httpStatus == 200) {
                    responseJson = JSON.parse(responseBody);
                    state = responseJson.state;

                    if (state === 'pending' || state === 'progress') {
                        gs.info('State is ' + state + '. Waiting for ' + delay / 60000 + ' minutes before next attempt.');
                        gs.sleep(delay);
                    }
                } else {
                    gs.error('Failed to get services. HTTP Status: ' + httpStatus);
                    return {
                        error: 'Failed to get services. HTTP Status: ' + httpStatus
                    };
                }
            }

            if (state !== 'pending' && state !== 'progress') {
                gs.info('Final Services Get Response: ' + JSON.stringify(responseJson));
                if (responseJson && responseJson.result && responseJson.result.length > 0) {
                    var services = responseJson.result[0].result[0].services;
                    for (var i = 0; i < services.length; i++) {
                        var service = services[i];
                        gs.info('Service Name: ' + service.name + ', State: ' + service.state);
                    }
                }
                return responseJson;
            } else {
                return {
                    error: 'Max attempts reached without a final state.'
                };
            }
        } catch (ex) {
            gs.error('Error while getting services: ' + ex.message);
            return {
                error: 'Error while getting services: ' + ex.message
            };
        }
    },

    type: 'GetServices1'
};

 


Please mark any helpful or correct solutions as such. That helps others find their solutions.
Mark

Hi Mark, I got this working over the weekend and another solution doing the same thing using glidedialogwindow both using asyncronous, give me a couple of hours and ill post all the code, I need to get the community article I used also. Big thank you for reaching and supporting with this.