GlideAjax — A Revisit
Posted on 29 Nov 2020 · 2 min read
I wrote about AJAX back in 2014, but I really like this topic so I thought it was worth revisiting with a fuller example.
Quick Recap: Synchronous vs Asynchronous
Synchronous is a real-time communication method where each party receives messages instantly, and the requestor needs to wait for the request to complete before continuing.
Asynchronous is a communication method where each party processes messages whenever it's possible to do so, rather than doing so immediately upon receipt. The requestor immediately continues with its work without waiting for a result.
When to Use GlideAjax
Use GlideAjax when you want to trigger a server-side function from the client side without reloading the entire form.
A Practical Example
Suppose a Service Desk manager wants customers to see their last opened incident when they try to report an outage. From a technical perspective, you need to:
- Get the User ID
- Query the Incident table where the caller equals the User ID
- Return and display the incident number
The only way to query server-side data from a client script is via a server call — and that means GlideAjax.
Step 1: Script Include
Create a client-callable Script Include that extends AbstractAjaxProcessor:
var AJAXLastINC = Class.create();
AJAXLastINC.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getLastINC: function() {
var vl = this.getParameter('sysparm_userid');
var gr = new GlideRecord('incident');
gr.addQuery('caller_id.sys_id', vl);
gr.orderByDesc('opened_at');
gr.query();
if (gr.next()) {
return 'Your last open Incident number ' + gr.number;
}
},
type: 'AJAXLastINC'
});
Step 2: Client Script
Create an onLoad client script to call the Script Include:
function onLoad() {
var ga = new GlideAjax('AJAXLastINC');
ga.addParam('sysparm_name', 'getLastINC');
ga.addParam('sysparm_userid', g_user.userID);
ga.getXML(GetUserINC);
}
function GetUserINC(response) {
var answer = response.responseXML.documentElement.getAttribute('answer');
alert(answer);
}
The key points here: sysparm_name tells the server which method to call, and getXML is asynchronous — the form won't hang waiting for a response.
Summary
| Concept | Detail |
|---|---|
| Script Include type | Client-callable, extends AbstractAjaxProcessor |
| Parameter passing | addParam('sysparm_name', 'methodName') |
| Execution | getXML(callbackFunction) — always async |
| Response reading | getAttribute('answer') on responseXML |