Submitting a client script based on AJAX response

Maciej Domagal1
Tera Contributor

I have an onSubmit Client Script that receives a boolean response from a Script Include. The script should prevent submitting/saving the record upon receiving the response 'false'.
This is the most basic script version:

function onSubmit() {
	var user = g_form.getValue('assigned_to');
	var needed_capacity = g_form.getValue('u_capacity');

	var ajax = new GlideAjax('SPOC_TicketAjaxUtils');
	ajax.addParam('sysparm_name', 'checkCapacity');
	ajax.addParam('sysparm_user', user);
	ajax.addParam('sysparm_capacity', needed_capacity);
	ajax.getXMLAnswer(handleResponse);

	function handleResponse(response) {
		g_form.addInfoMessage('Script Include Response: ' + response);

		if (response == 'false') {
			g_form.addErrorMessage("Assigning that ticket would exceed the user's maximum capacity of 100.");
			g_form.setValue('u_capacity', 0);
			return false;
		} 
	}
}

Even though the messages are correct, none of the submits are blocked. I tried multiple approaches, however none of them worked: I only managed to block every submit which is even worse. But I want to block the submit ONLY if the response is false.

1 ACCEPTED SOLUTION

Try below code:

 

function onSubmit() {
var user = g_form.getValue('assigned_to');
var needed_capacity = g_form.getValue('u_capacity');

var ajax = new GlideAjax('SPOC_TicketAjaxUtils');
ajax.addParam('sysparm_name', 'checkCapacity');
ajax.addParam('sysparm_user', user);
ajax.addParam('sysparm_capacity', needed_capacity);
ajax.getXMLWait();

var response = ajax.getAnswer();

if (response == 'false') {
g_form.addErrorMessage("Assigning that ticket would exceed the user's maximum capacity of 100.");
g_form.setValue('u_capacity', 0);
return false;
}
}

View solution in original post

4 REPLIES 4

Rahul Singh7
Tera Guru

getXMLAnswer() method is asynchronous in nature and they might not work with onSubmit client script because till they return answer onsubmit process might have been completed already.

So to avoid this situation you should use synchronous method i.e. getXMLWait().

Thank you. However, not only it didn't help, but made the situation even worse. Now every submit gets through and no message is displayed, just like the handleResponse function is never being called.

Do I need to change the order of the lines?

Try below code:

 

function onSubmit() {
var user = g_form.getValue('assigned_to');
var needed_capacity = g_form.getValue('u_capacity');

var ajax = new GlideAjax('SPOC_TicketAjaxUtils');
ajax.addParam('sysparm_name', 'checkCapacity');
ajax.addParam('sysparm_user', user);
ajax.addParam('sysparm_capacity', needed_capacity);
ajax.getXMLWait();

var response = ajax.getAnswer();

if (response == 'false') {
g_form.addErrorMessage("Assigning that ticket would exceed the user's maximum capacity of 100.");
g_form.setValue('u_capacity', 0);
return false;
}
}

Worked like a charm. Thank you so much!