Using GlideAjax with JSON in ServiceNow - ben-vargas/servicenow-wiki GitHub Wiki
GlideAjax allows for efficient, asynchronous communication between client-side scripts and server-side logic (via Script Includes) in ServiceNow. By returning data in JSON format, you simplify client-side data handling, improve code clarity, and enable more scalable solutions than traditional string parsing methods.
This guide shows how to use GlideAjax and JSON to pass parameters from client-side scripts, invoke server-side logic, and return structured results. It includes validation checks, error handling, and careful coding practices.
Why Use JSON with GlideAjax?
Compared to Traditional String Parsing:
Without JSON, multiple data points might be returned as a single delimited string that requires manual splitting. This approach is error-prone and can complicate code maintenance.
With JSON:
- Structured Data: Return a single JSON object with multiple fields. The client can parse once and access properties directly.
- Reduced Complexity: Adding or removing fields in the server response won’t break parsing logic on the client side.
- Scalability & Clarity: JSON is flexible and self-describing, making it easier to adapt as requirements change.
Client-Side Implementation
Below is a client-side script (e.g., a Client Script onChange
) using GlideAjax to retrieve and handle JSON data. It includes data validation, error handling, and property checks before accessing values.
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || !newValue) {
return;
}
var ga = new GlideAjax('ExampleAjax');
ga.addParam('sysparm_name', 'exampleMethod');
ga.addParam('sysparm_target_table', 'sys_user');
ga.addParam('sysparm_example_field_value', newValue);
ga.getXMLAnswer(function(responseJSON) {
if (!responseJSON || typeof responseJSON !== 'string') {
console.error('No valid JSON response received from server.');
return;
}
var parsedData;
try {
parsedData = JSON.parse(responseJSON);
} catch (parseError) {
console.error('Failed to parse JSON response:', parseError);
return;
}
if (parsedData.error) {
console.error('Server returned an error:', parsedData.error);
return;
}
if ('department_value' in parsedData && 'title' in parsedData) {
g_form.setValue('u_department', parsedData.department_value || '');
g_form.setValue('u_title', parsedData.title || '');
} else {
console.warn('Missing expected fields in the JSON response.');
}
});
}
Key Points:
- Checks input validity (
!newValue
). - Validates and parses the server response.
- Logs errors and warnings to help with debugging.
- Ensures required properties exist before using them.
Server-Side Script Include
The server-side Script Include processes incoming parameters, queries a record, and returns a JSON structure with appropriate checks and error handling.
var ExampleAjax = Class.create();
ExampleAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {
exampleMethod: function () {
var response = {
department_value: '',
department_display: '',
title: ''
};
var exampleSysId = this.getParameter('sysparm_example_field_value') || '';
var targetTable = this.getParameter('sysparm_target_table') || '';
if (!exampleSysId) {
return JSON.stringify({error: 'No sys_id provided.'});
}
if (!targetTable) {
return JSON.stringify({error: 'No target table provided.'});
}
var gr = new GlideRecord(targetTable);
if (!gr.isValid()) {
return JSON.stringify({error: 'Invalid target table specified.'});
}
if (gr.get(exampleSysId)) {
if (gr.isValidField('department')) {
response.department_value = gr.getValue('department') || '';
response.department_display = gr.department.getDisplayValue() || '';
}
if (gr.isValidField('title')) {
response.title = gr.getValue('title') || '';
}
} else {
return JSON.stringify({error: 'Record not found for the provided sys_id.'});
}
return JSON.stringify(response);
},
type: "ExampleAjax"
});
Key Points:
- Validates parameters before processing.
- Ensures the table and record exist.
- Checks for valid fields before accessing them.
- Returns an error object when issues occur, maintaining a consistent JSON response format.
Best Practices
-
Clear Parameter Naming:
Use descriptive parameter names for clarity. -
Error Handling:
Implement robust error handling on both client and server sides, returning or logging clear messages. -
Validation Before Access:
Check that fields and properties exist before using them to prevent null reference errors. -
Return Minimal Data:
Send only the data the client needs, improving performance and reducing complexity. -
Thorough Testing:
Test in a non-production environment, usinggs.info()
on the server andconsole.log()
on the client, to verify functionality before moving to production.
Additional Resources
-
ServiceNow Developer Site:
GlideAjax Documentation -
JSON Documentation:
MDN JSON Reference
Conclusion
By using GlideAjax with JSON, along with thorough validation and error handling, you ensure that your client and server code is maintainable, scalable, and easy to understand. This approach helps avoid the pitfalls of manual string parsing, making it simpler to adapt as your data requirements evolve.