Getting undefined value using GetReference method outside callback function

vivek72
Tera Guru

Hi,

I am using getReference method to check value set in a variable but getting undefined in alert:

Please let me know if I am missing anything, result in variable 'gr' should be test but I am getting undefined.

It's giving 'test' when I am trying to put alert inside callback function but the problem is only when this alert is set outside callback function.

I need to check this value to write my other code so it should return correct value outside callback function as well.

var gr;

var a1 = g_form.getReference('assignment_group', check);
function check(a1) {

if (a1.u_system == 'test') {

gr = a1.u_system;
}

}
alert(gr);

Thanks,

Vivek

Saurabh Gupta
Kilo Patron

Hi,

It is good practice to use GlideAjax instead of getReference().

 

You can use client script and client callable script include.

 

GlideAjax Example Cheat Sheet - Developer Community - Article - ServiceNow Community

 

If my answer replied your question please mark appropriate response as correct so that the question will appear as resolved for other users who may have a similar question in the future.

Regards,
Saurabh


Thanks and Regards,

Saurabh Gupta

Hi Saurabh,

Actually I need to run this script on button click on incident form, so this needs to be called via UI action. I am checking all mandatory fields and then calling server side code via this UI action.

I tired using your suggestion but code is running after all mandatory fields check on client side whereas this code should run before that.

Please suggest any way to run this before as I need to display message to user to proceed once all mandatory fields are filled in but right now I am getting mandatory field message after message is displayed to user.

Thanks,

Vivek

Hi,

Can you share your code please?


Thanks and Regards,

Saurabh Gupta

 

Here' the code, main problem is that alert inside callback function is showing correct value, alert outside function showing undefined value.

rest everything is in place if somehow I can display outer alert with correct value.

and if I check if condition inside callback function, it's fine but code is running after pop up to user and we need run it before that pop up so that users fills in mandatory fields.

var cmp;
var ga = new GlideAjax('TestSI');
ga.addParam('sysparm_name', 'getGroupCompany');
ga.addParam('sysparm_incident_sysid', g_form.getUniqueValue());
ga.addParam('sysparm_group_sysid', g_form.getValue('assignment_group'));
ga.getXML(getCompany);

function getcompany(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
var obj = JSON.parse(answer);
cmp = obj.company;
alert("cmp"+cmp);
}
alert(cmp);
if (cmp != 'test') {

g_form.showFieldMsg('assigned_to', 'Please select', 'error');
return false;

}

var answer = confirm("Please click ok to proceed.");
if (answer == false) {
return false;
}