ServiceNow GlideAjax Generator

Live

Describe what the form should do and get the client script and client-callable script include, matched and checked.

1 Where it runs

Script on
Runs
Why is there no “when the form is saved”?

A GlideAjax answer arrives after the save has already gone ahead, so an onSubmit script cannot wait for it. Check the value when the field changes instead, and stop bad saves on the server with a data policy or a before business rule.

2 What the server does

Fields to send back, and where they go
Reference sends the sys_id and the name, so a reference field on the form shows the name without another server call. Value sends what is stored, Display text what users see.

3 Also send optional

Form field on the left, parameter name on the right. The sysparm_ prefix is added for you.

4 Names

Application

When caller_id on incident changes, the client script sends its value to CallerInfoAjax.getCallerInfo(), which reads that sys_user record and fills in location and company.

Client script onChange

Script Checker: no problems
incident · caller_id
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading) {
        return;
    }
    if (newValue === '') {
        g_form.clearValue('location');
        g_form.clearValue('company');
        return;
    }

    var ga = new GlideAjax('CallerInfoAjax');
    ga.addParam('sysparm_name', 'getCallerInfo');
    ga.addParam('sysparm_user_id', newValue);
    ga.getXMLAnswer(function(answer) {
        var data = JSON.parse(answer || '{}');
        g_form.setValue('location', data.location.value, data.location.display);
        g_form.setValue('company', data.company.value, data.company.display);
    });
}

Script include client callable

Script Checker: no problems
CallerInfoAjax
var CallerInfoAjax = Class.create();
CallerInfoAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    getCallerInfo: function() {
        var userId = this.getParameter('sysparm_user_id');
        var result = {
            location: { value: '', display: '' },
            company: { value: '', display: '' }
        };
        var record = new GlideRecordSecure('sys_user');
        if (userId && record.get(userId)) {
            result.location = { value: record.getValue('location') || '', display: record.getDisplayValue('location') || '' };
            result.company = { value: record.getValue('company') || '', display: record.getDisplayValue('company') || '' };
        }
        return JSON.stringify(result);
    },

    type: 'CallerInfoAjax'
});

Set it up

1. Create the script include

  • Go to System Definition › Script Includes and click New.
  • Name: CallerInfoAjax. The API name becomes global.CallerInfoAjax.
  • Tick Client callable, then replace the generated script with the script include above.
  • When you save, recent releases may ask which roles may call it and create an access control for you (type client_callable_script_include, operation execute). Give it the roles of the people who use the form. If the call works for admins but not for others, check that access control.

2. Create the client script

  • Go to System Definition › Client Scripts and click New.
  • Table: incident. Type: onChange. Field name: caller_id.
  • UI Type: All, so it runs in the classic UI, workspaces and the Service Portal.
  • Paste the client script above.

3. Test it

  • Open an incident form and change caller_id.
  • Nothing happens? Look in the browser console for client errors, and in System Logs for server errors. A gs.info() line in the method shows whether it is called at all.
Open the Script Checker

How a GlideAjax call works

  1. The client script creates new GlideAjax() with the script include’s name, adds sysparm_name (the method) and its own sysparm_ values.
  2. getXMLAnswer() sends them to the server without freezing the form, and calls back when the answer arrives.
  3. The script include extends AbstractAjaxProcessor, reads each value with this.getParameter() and returns a string, usually JSON.
  4. The callback parses the JSON and updates the form with g_form.

Need the API calls? The GlideAjax cheat sheet lists every method with examples.

Mistakes the generated code avoids

Parameter without sysparm_
GlideAjax only passes parameters named sysparm_…; others arrive empty.
Returning an object
The client receives "[object Object]". Return JSON.stringify() and parse it.
getXMLWait()
Freezes the form and does not work in the Service Portal.
No isLoading check
The onChange script also runs as the form loads, with an extra server call each time.
GlideRecord in the script include
Ignores ACLs: anyone who can call the method can read the records.
Wrong base class in a scoped app
Scoped script includes extend global.AbstractAjaxProcessor.
A method called initialize or process
Replaces the parent’s method, and every call fails.

Who can call a client-callable script include?

Anyone who is logged in can call it from the browser, with any parameter values they like. ACLs on the form do not protect it, so the script include protects itself: it reads records with GlideRecordSecure so the caller’s ACLs apply, it matches values with addQuery() so a value cannot add its own conditions, and it returns only the fields the form needs. On top of that, an access control of type client_callable_script_include decides which roles may call it at all.

Before you reach for GlideAjax

  • Data for when the form opens: a display business rule puts it in g_scratchpad, with no extra request.
  • The current user: g_user.userID, g_user.getFullName() and g_user.hasRole() are already in the browser. Check roles again on the server for anything that matters.
  • Show, hide or require fields from values on the form: a UI policy does it without a script.

Frequently asked questions

Where is GlideAjax used in ServiceNow?

Anywhere a script runs in the browser and needs data the page does not have: onChange client scripts (the most common: fill in or check something when a field changes), onLoad client scripts, client-side UI actions (a button, context menu item or link that asks the server something), catalog client scripts on catalog items, record producers and variable sets, and onCellEdit scripts that check a list edit before it is saved. The generator covers all five. Rarer places, such as UI policy scripts and UI pages, use the same pattern: start from Write my own. Service Portal widgets and UI Builder pages do not use GlideAjax; they have their own server scripts and data resources.

What is GlideAjax in ServiceNow?

GlideAjax lets a client script call server code without reloading the form. The client script names a client-callable script include and a method, sends values as sysparm_ parameters, and gets a string back, usually JSON. It is the standard way to read data the form does not have, for example the location of the selected caller.

What is the difference between getXMLAnswer, getXML and getXMLWait?

getXMLAnswer(callback) passes the answer string straight to your callback, which is the simplest. getXML(callback) passes the whole response, and you read the answer attribute yourself. getXMLWait() waits for the server and freezes the form while it does; it is not available in the Service Portal. Use getXMLAnswer.

How do I call a script include from a client script in a scoped app?

Extend global.AbstractAjaxProcessor in the script include, tick Client callable, and call it from the client with its API name, for example new GlideAjax('x_acme_app.CallerInfoAjax'). If the client script is in another scope, set the script include’s Accessible from to All application scopes. Choose “A scoped app” above and the generator does all of this.

Why does my GlideAjax call work for admins but not for other users?

Client-callable script includes can be protected by an access control of type client_callable_script_include with the operation execute. Recent releases may create one when you save the script include, with the roles you choose. If a user does not have one of those roles, the call fails. Add the roles of the people who use the form to that access control.

Is a client-callable script include secure?

Any logged-in user can call it from the browser with any parameters, so treat the parameters as untrusted. Read records with GlideRecordSecure so ACLs apply, use addQuery() rather than building encoded queries from input, and do not add isPublic() returning true unless the data is truly public. The generated code follows all three rules.

When should I not use GlideAjax?

For data the form needs as it opens, a display business rule that fills g_scratchpad avoids a second request. For the current user’s name or roles, g_user already has them. For showing and hiding fields based on values already on the form, a UI policy needs no script at all.

Does the generator work for catalog items, record producers and the Service Portal?

Yes. Choose “A catalog item or record producer” and the script uses your variable names, with setup steps for a catalog client script. To reuse it on several items, attach it to a variable set. The code uses getXMLAnswer and g_form only, which work in the Service Portal and in workspaces. Set UI Type to All.

Can I use GlideAjax in an onSubmit client script?

Not reliably. GlideAjax answers asynchronously, so the save has already gone ahead when the answer arrives, and the synchronous getXMLWait() freezes the form and does not work in the Service Portal. Check the value in an onChange script as the user fills in the form, and stop bad saves on the server with a data policy or a before business rule.