Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Scripting

Client Scripts and g_form in ServiceNow

Learn ServiceNow client scripts: onLoad, onChange, onSubmit and onCellEdit, the g_form and g_user APIs, GlideAjax for server data, and when to use UI policies instead.

Server scripts run in the data center. Client scripts run in the user's browser while a form is open. They make forms react at once: hide a field, set a value when a choice changes, or stop a bad submission before the round trip to the server. Because they run in the browser, they can never be trusted for security: a determined user can bypass them, so enforce important rules on the server as well.

Client scripts need a ServiceNow form in a browser. The script samples are read-only. The runnable blocks are stand-ins: a tiny imitation of the g_form API in JavaScript.

Types of client script

Create them in System Definition > Client Scripts (or via the form's context menu in Studio). Choose a Type:

Type Runs when Typical use
onLoad The form finishes loading Hide fields, set defaults, show messages
onChange A chosen field changes Fill dependent fields, react to choices
onSubmit The user clicks Submit/Save Validate, then return false to stop
onCellEdit A list cell is edited inline Validate list edits

The function signature differs by type. onChange receives control, oldValue, newValue, isLoading, isTemplate.

JavaScript
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
  if (isLoading || newValue === '') {
    return;                                  // do nothing while the form loads
  }
  if (newValue == '1') {                     // Priority 1
    g_form.setMandatory('work_notes', true);
    g_form.showFieldMsg('priority', 'Add work notes for critical incidents.', 'info');
  } else {
    g_form.setMandatory('work_notes', false);
  }
}

Always start an onChange with the isLoading guard. Otherwise your code also runs while the form loads existing data, which is rarely intended.

g_form: the form API

Method Effect
g_form.getValue('f') Read the stored value
g_form.setValue('f', v) Set a value
g_form.setMandatory('f', true) Make required
g_form.setReadOnly('f', true) Lock
g_form.setDisplay('f', false) Hide (also removes the space)
g_form.setVisible('f', false) Hide but keep the space
g_form.addInfoMessage('text') / addErrorMessage Message at the top
g_form.showFieldMsg('f', 'text', 'error') Message under a field
g_form.addOption / removeOption Change choice lists
g_form.clearValue('f') Empty a field

Other client globals: g_user (current user: g_user.userName, g_user.hasRole('itil')), g_list for list pages and g_navigation for opening URLs.

onSubmit validation

JavaScript
function onSubmit() {
  var notes = g_form.getValue('close_notes');
  if (g_form.getValue('state') == '6' && notes.length < 20) {
    g_form.addErrorMessage('Please write at least 20 characters of close notes.');
    return false;                            // stops the submit
  }
}

Returning false cancels the submit. No return means it continues.

Getting server data with GlideAjax

Browsers cannot run GlideRecord directly (the synchronous GlideRecord client API is discouraged and slows forms). The standard way is GlideAjax, which calls a client-callable Script Include on the server.

JavaScript
function onChange(control, oldValue, newValue, isLoading) {
  if (isLoading || !newValue) return;
  var ga = new GlideAjax('UserLookupAjax');
  ga.addParam('sysparm_name', 'getDepartment');
  ga.addParam('sysparm_user', newValue);
  ga.getXMLAnswer(function (answer) {       // asynchronous callback
    g_form.setValue('u_department', answer);
  });
}

The server half is a Script Include (next lesson) that extends AbstractAjaxProcessor. Use getXMLAnswer with a callback, never a synchronous call that freezes the browser.

Client script or UI policy?

Choose a UI policy whenever the need is "show, hide, make mandatory or read-only when a condition holds". UI policies need no code, run on both load and change, and are easier to maintain. Use a client script when you need real logic, calculations, or server data. You will configure UI policies in the previous chapter on forms.

A g_form stand-in

The next block models a form and a few g_form methods in plain JavaScript. It is not the real API, but your logic can be practiced as if it were.

JS Stand-in: g_form and an onChange rule

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in models an onSubmit validation returning false.

JS Stand-in: onSubmit that can block

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Mistakes to avoid

  1. Forgetting the isLoading guard in onChange.
  2. Relying on a client script for security; repeat important rules in a business rule or ACL.
  3. Using synchronous server calls (getRefRecord, sync GlideRecord) in forms.
  4. Hard-coding sys_ids in scripts.
  5. Setting Global scope scripts for tables you do not own.
  6. Using a client script where a UI policy would do.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should onChange scripts begin with an isLoading check?

    onChange also fires while the form initializes; the guard avoids unwanted effects on load.
  2. 2. How does an onSubmit client script stop the submit?

    Returning false cancels the submit.
  3. 3. What is the recommended way to fetch server data from a client script?

    GlideAjax calls a client-callable Script Include asynchronously.
  4. 4. A requirement says 'make Close notes mandatory when State is Resolved'. What is usually best?

    UI policies handle show, hide, mandatory and read-only conditions without code.

Summary

  • Client scripts run in the browser: onLoad, onChange, onSubmit and onCellEdit.
  • g_form reads and changes form fields; g_user describes the current user.
  • Use GlideAjax for server data and UI policies for simple visibility and mandatory rules.
  • Client logic is a convenience; enforce critical rules on the server.

Next: Script Includes, UI Actions and Scheduled Jobs