← All guides

ServiceNow GlideAjax: Call a Script Include from a Client Script

How to use GlideAjax in ServiceNow to call a client-callable Script Include from a client script, return JSON, and keep the call fast and secure.

GlideAjax is how a ServiceNow client script calls a Script Include on the server without freezing the form. You write a client-callable Script Include that extends AbstractAjaxProcessor, then in the client script you create a GlideAjax object with the Script Include name, pass the method name in sysparm_name, add your own sysparm_ parameters, and read the result in a getXMLAnswer() callback. That is the whole pattern. The rest of this guide builds a working example and covers the parts that cause most bugs: return values, scope names and security.

When to use GlideAjax

Use GlideAjax when the browser needs server data after the form has loaded, usually in an onChange client script. Typical cases are looking up a user's department when the caller changes, checking whether a CI is in a maintenance window, or validating a value against a table the user cannot see on the form.

If the data is needed when the form opens, a display business rule that fills g_scratchpad is cheaper because it rides along with the form load. The client script best practices guide covers that choice in more detail.

OptionWhen it runsBlocks the formWorks in Service PortalGood for
g_scratchpad from a display business ruleForm loadNoYesData needed on load
GlideAjax with getXMLAnswer()On demandNoYesData needed after a change
GlideAjax with getXML()On demandNoYesSame, when you want the full response
g_form.getReference() with a callbackOn demandNoYesOne field from one referenced record
GlideAjax with getXMLWait()On demandYesNoAvoid
Client-side GlideRecordOn demandUsuallyNoAvoid

Step 1: Create the client-callable Script Include

Go to System Definition > Script Includes and create a new record. Select Client callable. The class must extend AbstractAjaxProcessor, which provides getParameter() and handles the request plumbing.

This example returns a caller's VIP flag, department and manager as JSON:

var CallerInfoAjax = Class.create();
CallerInfoAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {

  getCallerInfo: function() {
    var userId = this.getParameter('sysparm_user_id');

    // Reject anything that is not a sys_id before touching the database
    if (!userId || !/^[0-9a-f]{32}$/.test(userId)) {
      return JSON.stringify({ ok: false, error: 'invalid_user' });
    }

    // Only users who can work incidents need this data
    if (!gs.hasRole('itil')) {
      return JSON.stringify({ ok: false, error: 'not_allowed' });
    }

    // GlideRecordSecure applies ACLs for the calling user
    var user = new GlideRecordSecure('sys_user');
    if (!user.get(userId)) {
      return JSON.stringify({ ok: false, error: 'not_found' });
    }

    return JSON.stringify({
      ok: true,
      vip: String(user.vip) == 'true',
      department: user.getDisplayValue('department'),
      manager: user.getDisplayValue('manager')
    });
  },

  type: 'CallerInfoAjax'
});

A few rules this example follows:

  • Return a string. The return value becomes the answer the client receives. Build an object and pass it through JSON.stringify() when you need more than one value.
  • Read input with this.getParameter(). Custom parameter names must start with sysparm_.
  • Keep the method small. It runs on every call, so query only what you need and avoid loops over large tables. The GlideRecord query performance guide applies here too.

In a scoped application, extend global.AbstractAjaxProcessor instead:

var CallerInfoAjax = Class.create();
CallerInfoAjax.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
  // methods as above
  type: 'CallerInfoAjax'
});

Step 2: Call it from the client script

Create an onChange client script on the Incident table for the Caller field:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
  if (isLoading || newValue === '') {
    g_form.hideFieldMsg('caller_id', true);
    return;
  }

  var ga = new GlideAjax('CallerInfoAjax');
  ga.addParam('sysparm_name', 'getCallerInfo');
  ga.addParam('sysparm_user_id', newValue);
  ga.getXMLAnswer(function(answer) {
    var result;
    try {
      result = JSON.parse(answer);
    } catch (e) {
      return; // Empty or unexpected response; leave the form as it is
    }

    g_form.hideFieldMsg('caller_id', true);
    if (!result.ok) {
      return;
    }

    if (result.vip) {
      g_form.showFieldMsg('caller_id', 'VIP caller', 'info');
    }
    if (result.department) {
      g_form.addInfoMessage('Department: ' + result.department +
        (result.manager ? ', manager: ' + result.manager : ''));
    }
  });
}

What each line does:

  • new GlideAjax('CallerInfoAjax') names the Script Include. If the Script Include is in a scoped application, use its full API name, for example new GlideAjax('x_acme_helpdesk.CallerInfoAjax').
  • sysparm_name is the method to run. It must match the method name exactly, including case.
  • getXMLAnswer() sends the request and calls your function with the answer string. Code after this line runs immediately, before the answer arrives.

The library has a ready GlideAjax server call, a response handler Script Include and a multi-function GlideAjax utility you can adapt.

getXMLAnswer vs getXML

getXMLAnswer() is the shorter form and the one to use by default. getXML() passes the full response object to the callback, and you read the answer yourself:

var ga = new GlideAjax('CallerInfoAjax');
ga.addParam('sysparm_name', 'getCallerInfo');
ga.addParam('sysparm_user_id', g_form.getValue('caller_id'));
ga.getXML(function(response) {
  var answer = response.responseXML.documentElement.getAttribute('answer');
  var result = JSON.parse(answer);
  // use result
});

Both are asynchronous. You will see getXML() in older code; there is no need to convert working scripts, but new scripts are easier to read with getXMLAnswer().

Why not getXMLWait

getXMLWait() waits for the server before the next line runs, then you read the result with ga.getAnswer(). It looks convenient, especially in onSubmit scripts, but the browser is frozen while it waits and it does not work in Service Portal.

The usual reason people reach for it is an onSubmit check that needs server data. An asynchronous callback cannot cancel a submit because the function has already returned. Do the lookup earlier, in an onChange, store the result, and let onSubmit check it locally. Back the rule with a business rule on the server, because onSubmit does not run for list edits, imports or integrations.

Security: treat every call as public

A client-callable Script Include is an endpoint. Any logged-in user can call it from the browser console with any method name and any parameter values. Your client script being on an ITIL-only form does not restrict who can call the server side.

Checklist for every client-callable method:

  • Check the caller's roles with gs.hasRole() before returning anything sensitive.
  • Validate every sysparm_ value: type, format and length.
  • Query with GlideRecordSecure so access controls apply, not GlideRecord.
  • Return only the fields the client needs, never a whole record.
  • Never build an encoded query by concatenating raw input. Use addQuery() with separate field and value arguments.
  • Do not override isPublic() to return true unless the method must work for users who are not logged in and returns nothing sensitive.

If a GlideAjax call returns not_allowed for a user who should have access, the ACL troubleshooting guide walks through finding the rule that blocks them.

Debugging a GlideAjax call that returns nothing

Work through these in order:

  1. Client callable is not selected. This is the most common cause.
  2. Name mismatch. The GlideAjax class name and the sysparm_name method name are case-sensitive. Check the scope prefix for scoped Script Includes.
  3. Wrong base class. The Script Include must extend AbstractAjaxProcessor (or global.AbstractAjaxProcessor in a scope).
  4. The method returns nothing. A method that ends without return sends an empty answer. Make sure every path returns a string.
  5. A server error. Add gs.info('getCallerInfo called with ' + userId); at the top of the method and check System Logs > System Log > All.
  6. The request itself. Open the browser developer tools, filter the network tab on xmlhttp.do, and inspect the request parameters and the response body.

Keep calls cheap

Each GlideAjax call is a round trip to the server. A few habits keep forms fast:

  • Return several values in one JSON response instead of making one call per field.
  • Skip the call when isLoading is true or the new value is empty.
  • Cache values that rarely change. The session caching guide shows one way to do this on the server.
  • Group related methods in one Script Include per table or feature, so they are easy to find and review.

Summary checklist

  • Script Include extends AbstractAjaxProcessor and has Client callable selected
  • Method names match sysparm_name exactly
  • Custom parameters start with sysparm_ and are validated
  • Methods return a string, using JSON for multiple values
  • Client uses getXMLAnswer() with a callback, never getXMLWait()
  • Roles checked and GlideRecordSecure used on the server
  • onSubmit rules are backed by a server-side business rule

For more patterns that pair well with GlideAjax, see the ServiceNow coding best practices checklist and the business rule best practices guide.

Frequently asked questions

What is GlideAjax in ServiceNow?

GlideAjax is a client-side API that sends a request from the browser to a client-callable Script Include on the server and hands the result back to a callback function. It lets a client script use server data without client-side GlideRecord.

Why does my GlideAjax call return null?

The most common causes are: the Client callable box is not selected on the Script Include, the sysparm_name value does not match a method name, the Script Include does not extend AbstractAjaxProcessor, the class name is misspelled or missing its scope prefix, or the method returns nothing. Add gs.info() lines to the method and check the system log to see whether it runs at all.

Should I use getXMLAnswer or getXMLWait?

Use getXMLAnswer with a callback. It is asynchronous, so the form stays responsive. getXMLWait is synchronous, freezes the browser until the server replies, and is not supported in Service Portal.

Is a client-callable Script Include secure by default?

No. Any logged-in user can call it from the browser with any parameter values, regardless of which form your client script runs on. Check roles inside the method, validate every parameter, and query with GlideRecordSecure so access controls apply.

More practical ServiceNow notes.

Back to the guides