Client callable Script Include returning null to UI Action

davilu
Mega Sage

Hello experts, I can't figure what I'm doing wrong.  I have a UI Action that calls a Script Include.  When I log my Script Include, I'm seeing the correct value returning, but when I set up alerts in my UI Action, the alerts are returning null.

 

Script Include method:

closeTask: function() {
        var tblName = this.getParameter("sysparm_table_name");
        var sysId = this.getParameter("sysparm_sys_id");
        var newNote = this.getParameter("sysparm_new_note");

        this.closeHRTaskWithComment(tblName, sysId, newNote);
    },
 closeHRTaskWithComment: function(table, uniqueID, comment) {

        var response = {};
        var hrTaskGR = new GlideRecord(table);

        if (hrTaskGR.get(uniqueID)) {
            if (hrTaskGR.canWrite()) {
                this._updateNotes(hrTaskGR, comment, false);
                this._workEnd(hrTaskGR);

                hrTaskGR.state = hr.STATE_CLOSE_COMPLETE;
                response.success = hrTaskGR.update() ? true : false;
            } else
                response.error = 'No write access to record.';
        } else 
            response.error = 'Record not found.';
	        gs.info('dlu ' + JSON.stringify(response))
        return JSON.stringify(response);
    },

When I check the logs, I see this:

davilu_0-1731104165101.png

 

My Workspace UI Action looks like this:

function onClick(g_form) {
    getMessages(['Work Notes', 'Provide a summary of the work performed'], function() {
        var sysId = typeof rowSysId == 'undefined' || rowSysId == null ? g_form.getUniqueValue() : rowSysId;
        //Setup the fields for modal
        var fields = [{
            type: 'textarea',
            name: 'work_notes',
            label: getMessage('Work Notes'),
            mandatory: true
        }];
        //Create the modal	
        g_modal.showFields({
            title: getMessage('Provide a summary of the work performed'),
            fields: fields,
            size: 'md'
        }).then(function(fieldValues) {
            //Get the new worknote
            var newWorkNote = fieldValues.updatedFields[0].value;
            //Call to GlideAjax to close the task
            var gA = new GlideAjax("sn_hr_core.hr_CaseAjax");
            gA.addParam("sysparm_name", "closeTask");
            gA.addParam("sysparm_table_name", g_form.getTableName());
            gA.addParam("sysparm_sys_id", g_form.getUniqueValue());
            gA.addParam("sysparm_new_note", newWorkNote);
            gA.getXML(saveForm);

            function saveForm(response) {
                var answer = response.responseXML.documentElement.getAttribute("answer");
                answer = JSON.parse(answer);
                alert('here? ' + answer)

                g_form.save().then(function() {
                    //g_aw.closeRecord();
                });
            }
        });
    });
}

 

My alert returns null:

davilu_1-1731104261571.png

Any idea what I'm missing?

 

 

6 REPLIES 6

Runjay Patel
Giga Sage

Hi @davilu,

 

I fount your issue. Issue is in your response function. You should not use JSON.pars, without this it will also work.

 

Use below code.

function saveForm(response) {
                var answer = response.responseXML.documentElement.getAttribute("answer");
                answer = answer.evalJSON();
                alert('here? ' + answer.success)

                g_form.save().then(function() {
                    //g_aw.closeRecord();
                });
            }

 

-------------------------------------------------------------------------

If you found my response helpful, please consider selecting "Accept as Solution" and marking it as "Helpful." This not only supports me but also benefits the community.


Regards
Runjay Patel - ServiceNow Solution Architect
YouTube: https://www.youtube.com/@RunjayP
LinkedIn: https://www.linkedin.com/in/runjay

-------------------------------------------------------------------------

Thanks for your suggestion Runjay!  I tried your code but i'm getting strange result.  When I replace with your code and click the UI Action, nothing happens and I see this error in the console:

 

GlideScopedScript.js:111 SCRIPT:EXEC Error while running Client Script "GlideScopedScript": TypeError: Cannot read properties of undefined (reading 'apply')

 

I then deleted your script and clicked the UI Action again and still nothing happens and I see the same console error above.  

 

It is only after I revert back to my previous version does the UI action bring up the modal again and without the console error. 

 

Any thoughts on what's going on?  Thanks!

Not applicable

Hello @davilu 

 

I see that "JSON.stringify(response)" is used twice in script include. Sometimes when using JSON.stringify twice gives unintended result. Try after commenting the gs.info line.

	        gs.info('dlu ' + JSON.stringify(response))
        return JSON.stringify(response);

 In client script try the code 

var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer) {  // Check if answer is not null or empty
    try {
        answer = JSON.parse(answer);  // Parse if answer is valid JSON
    } catch (e) {
        console.error("Parsing error: ", e);
    }
} else {
    console.warn("No answer attribute found or attribute is empty.");
}

This way, if the answer is not in JSON format, it won’t throw an error, and you’ll get a clear indication in the console.

 

*************************************************************************************************************
"If you found my answer helpful, please give it a like and mark it as the "accepted solution". It helps others find the solution more easily and supports the community!"

Thank You
Juhi Poddar
****************************************************************************************************************

Thais JuhiPoddar, I gave your suggestions a try.  I changed my Script Include to look like this:

 

closeTask: function() {
        var tblName = this.getParameter("sysparm_table_name");
        var sysId = this.getParameter("sysparm_sys_id");
        var newNote = this.getParameter("sysparm_new_note");

        this.closeHRTaskWithComment(tblName, sysId, newNote);
    },
    closeHRTaskWithComment: function(table, uniqueID, comment) {

        var response = {};
        var hrTaskGR = new GlideRecord(table);

        if (hrTaskGR.get(uniqueID)) {
            if (hrTaskGR.canWrite()) {
                this._updateNotes(hrTaskGR, comment, false);
                this._workEnd(hrTaskGR);

                hrTaskGR.state = hr.STATE_CLOSE_COMPLETE;
                response.success = hrTaskGR.update() ? true : false;
            } else
                response.error = 'No write access to record.';
        } else 
            response.error = 'Record not found.';
	
        var json = JSON.stringify(response);
		gs.info('dlu ' + json)
		return json;

    },

 

For the UI Action, it has been changed to:

 

function onClick(g_form) {
    submitTask(g_form);
}

function submitTask(g_form) {
    var fields = [{
        type: 'textarea',
        name: 'work_notes',
        label: getMessage('Work Notes'),
        mandatory: true
    }];
    //Create the modal	
    g_modal.showFields({
        title: getMessage('Provide a summary of the work performed'),
        fields: fields,
        size: 'md'
    }).then(function(fieldValues) {
        //Get the new worknote
        var newWorkNote = fieldValues.updatedFields[0].value;

        //Call to GlideAjax to close the task
        var gA = new GlideAjax("sn_hr_core.hr_CaseAjax");
        gA.addParam("sysparm_name", "closeTask");
        gA.addParam("sysparm_table_name", g_form.getTableName());
        gA.addParam("sysparm_sys_id", g_form.getUniqueValue());
        gA.addParam("sysparm_new_note", newWorkNote);
        gA.getXML(saveForm);

        function saveForm(response) {
            var answer = response.responseXML.documentElement.getAttribute("answer");
 	   alert(answer)

            if (answer) { // Check if answer is not null or empty
                try {
                    answer = JSON.parse(answer); // Parse if answer is valid JSON
                } catch (e) {
                    console.error("Parsing error: ", e);
                }
            } else {
                console.warn("No answer attribute found or attribute is empty.");
            }

            g_form.save().then(function() {
                //g_aw.closeRecord();
            });
        }
    });
}

 

My gs.info from the Script Include still returns:

dlu {"success":false} 

which makes me believe that the Script Include is working fine.

 

My alert in the UI Action still returns null and I see the console warning:

davilu_0-1731177117271.png

 

There's something happening where that false value isn't getting to the UI Action for some reason...