GlideAjax is a powerful feature of ServiceNow that allows you to make asynchronous calls to server-side scripts from client-side scripts. It can be used to perform complex calculations, validate data, update records, or execute any custom logic that cannot be done on the client side.
In this blog post, I will show you how to use GlideAjax in ServiceNow scripts with some examples and best practices.
The basic steps to use GlideAjax are:
1. Create a server-side script include that extends the AbstractAjaxProcessor class and contains one or more public methods that return data to the client.
2. Create a client-side script that instantiates a GlideAjax object and passes the name of the script include and the method to call.
3. Define a callback function that receives the response from the server and handles it accordingly.
4. Call the getXML() or getXMLAnswer() method of the GlideAjax object to send the request to the server.
Let's see an example of how to use GlideAjax in a client script on a form.
Suppose we have a script include called MyUtils that has a public method called getFullName that takes a user sys_id as a parameter and returns the user's full name.
The script include would look something like this:
var MyUtils = Class.create();
MyUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getFullName: function() {
var sys_id = this.getParameter('sysparm_sys_id');
var user = new GlideRecord('sys_user');
if (user.get(sys_id)) {
return user.getDisplayValue();
}
return '';
},
type: 'MyUtils'
});
The client script would look something like this:
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
//Create a GlideAjax object and pass the name of the script include
var ga = new GlideAjax('MyUtils');
//Pass the name of the method and the parameter
ga.addParam('sysparm_name', 'getFullName');
ga.addParam('sysparm_sys_id', newValue);
//Define a callback function
ga.getXML(function(response) {
//Get the answer from the response
var answer = response.responseXML.documentElement.getAttribute('answer');
//Display an alert with the answer
alert('The full name of the assigned user is ' + answer);
});
}
Some best practices to follow when using GlideAjax are:
Use descriptive names for your script includes and methods.
Use sysparm_ prefix for your parameters to avoid conflicts with system parameters.
Use getXMLAnswer() instead of getXML() if you only need the answer and not the whole XML response.
Use try/catch blocks and gs.log() statements in your server-side scripts to handle errors and debug issues.
Use appropriate security checks in your server-side scripts to prevent unauthorized access or data manipulation.
Use GlideAjax sparingly and only when necessary, as it adds overhead to the server and the network.
I hope this blog post helped you understand how to use GlideAjax in ServiceNow scripts. If you have any questions or feedback, please leave a comment below.
Comentários