Prevent Form Submission Until GlideAjax Validation Completes in ServiceNow

The form submission won't stop automatically when using GlideAjax for validation in the onSubmit method because this is an asynchronous call.

You can use the following approach to ensure the form doesn't submit until validation is completed and passed. Refer to the code below for implementation details:


PORTAL:
function onSubmit() {
// Check if the form is already marked as valid in the scratchpad
if (g_scratchpad.isFormValid) {
return true; // If valid, allow the form to be submitted
}
// Get the name of the action being performed (e.g., save, update)
var actionName = g_form.getActionName();
//GlideAjax
var ga = new GlideAjax("YourScriptIncludeName");
ga.addParam("sysparm_name", "YourMethodName");
ga.getXMLAnswer(function(answer) {
// Check the answer returned by the script include method
if (answer == 'true') {
g_scratchpad.isFormValid = true;
g_form.submit(actionName);
} else {
g_scratchpad.isFormValid = false;
}
});
// Prevent the form from submitting immediately (*IMP*)
return false;
} FULFILLER: 

function onSubmit() {
var getTransApp = new GlideAjax('YourScriptIncludeName');
getTransApp.addParam('sysparm_name', 'YourMethodName');
getTransApp.getXMLWait();
var answer = getTransApp.getAnswer();
if (answer == 'true') {
g_form.setValue('position', answer);
} else {
g_form.addErrorMessage('Error');
return false;
}
}

We can't use the XMLWait for Portal, It will throw the below error!