Reputation: 11
I am writing an onChange Client Script in ServiceNow and having issues with a Javascript error on the front end client. I keep getting a TypeError: Cannot read property 'u_emp_name' of undefined. the variable seems to vary as at one point i was getting the u_pos_office undefined as well, however the data is pulling correctly and there are no performance impacts on my code functionality.
What could be causing the type error?
Script is below:
function onChange(control, oldValue, newValue, isLoading) {
var billNum = g_form.getReference('u_billet',findBilletInfo);
console.log('Emp Name: ' + billNum.u_emp_name);
console.log('OFfice: ' + billNum.u_pos_office);
console.log('Career Field: ' + billNum.u_pos_career_field);
if (isLoading || newValue == '') {
return;
}
if (oldValue != newValue){
findBilletInfo(billNum);
}
function findBilletInfo(billNum){
console.log('Bill Num' + billNum);
console.log('encumbent' + billNum.u_emp_name);
var empName = billNum.u_emp_name;
var empNameStr = empName.toString();
console.log(empName);
console.log(empNameStr);
g_form.setValue('u_organization_office',billNum.u_pos_office);
g_form.setValue('u_encumbent',billNum.u_emp_name);
g_form.setValue('u_old_career_field',billNum.u_pos_career_field);
g_form.setValue('u_old_career_specialty',billNum.u_pos_career_specialty);
g_form.setValue('u_old_occupational_series',billNum.u_pos_series);
g_form.setValue('u_old_grade',billNum.u_pos_grade);
g_form.setValue('u_old_work_category',billNum.u_pos_category);
g_form.setValue('u_old_job_title',billNum.u_pos_title);
g_form.setValue('u_losing_rater',billNum.u_emp_rater_name);
g_form.setValue('u_losing_reviewer',billNum.u_emp_reviewer_name);
}
}
Upvotes: 1
Views: 6761
Reputation: 16255
It appears to be an error here
var billNum = g_form.getReference('u_billet',findBilletInfo);
==> console.log('Emp Name: ' + billNum.u_emp_name);
In this case billNum
is undefined since getReference
is run asynchronously. See the documentation for the function.
This means that it won't guarantee a return value immediately or at all. This is probably why you get a record sometimes and not others.
You can move these debug logs within your findBilletInfo
callback to check the values
if (isLoading || newValue == '') {
return;
}
var billNum = g_form.getReference('u_billet',findBilletInfo);
function findBilletInfo(billNum) {
console.log('Bill Num' + billNum);
console.log('encumbent' + billNum.u_emp_name);
console.log('OFfice: ' + billNum.u_pos_office);
console.log('Career Field: ' + billNum.u_pos_career_field);
...
}
If you debug in Firefox or Chrome, you should be able to just log the object to the console to explore the entire object at once.
function findBilletInfo(billNum) {
console.log(billNum);
...
}
The output will look like something like this in the console and you can see all fields at once.
Upvotes: 2