user2183592 user2183592 - 1 year ago 224
Javascript Question

ServiceNow Javascript passing variables from GlideAjax functions

I am using ServiceNow. I need to validate a form onSubmit. I am using GlideAjax with a script include to validate data. How can I pass variables from the Ajax function calendarDate(response) to other functions within the Client Script? When the glide ajax function returns an error message, I want to set the variable "isValid" to false.

I have done this easily with Client Scripts that do not involve GlideAjax. I simply set the variable isValid to the result of the function such as var isValid = checkLnrDates();

However, setting a variable equal to the function call when using GlideAjax does not return any value that I can use. I perhaps am not understanding the way that the GlideAjax functions are called and handled.

Catalog Client Script onSubmit

function onSubmit () {
var isValid = checkLnrDates();
if (isValid == false) {
g_form.submitted = false;
return false;

function checkLnrDates() {
var start = g_form.getValue('start_date');
//Check calendar date format valid YYYY-MM-DD
//Script include ClientDateTimeUtils checks the input data
var ajaxCalendarDate = new GlideAjax('ClientDateTimeUtils');
ajaxCalendarDate.addParam('sysparm_name', 'validateCalendarDate');
ajaxCalendarDate.addParam('sysparm_userDate', start);

function calendarDate(response){
//This is where we get the response returned from the ClientDateTimeUtils script include ajax function
var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer != 'true'){
g_form.showFieldMsg('start_date', answer,'error');
//How can I pass the value of a variable to the function above? I want to set isValid to false
isValid = false;
return false;

Answer Source

The fact that you need to get a response from the AJAX round-trip before you can proceed means that you're not actually asynchronous. You could probably just call ajaxCalendarDate.getXMLWait() and then call ajaxCalendarDate.getAnswer() to get the response synchronously (see Synchronous GlideAjax)

However, since you're already submitting, and your code relies on a server-side function call to validate some input, you might just consider moving this logic into a Before Insert Business Rule that validates, and aborts using current.setAbortAction(true) if your validation fails. Wiki example here.

Your business rule would look something like:

function onBefore(current, previous) {
  if (!CliendDateTimeUtils.validateCalendarDate(current.start_date)) {
    current.setAbortAction(true); // Don't save the record
    gs.addErrorMessage("Start date is not valid"); // Add an error message for the user
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download