Understanding ServiceNow Data Access Methods and GlideAjax Implementation Challenges
Mack ISLAM
ServiceNow Developer | Crafting tailored ServiceNow solutions for optimal efficiency
Introduction
Modern enterprise applications demand robust and efficient data handling mechanisms. ServiceNow, as a leading enterprise platform, provides various methods for accessing and manipulating data across its ecosystem. This technical documentation explores these methods in depth, with particular focus on GlideAjax implementations in Catalog Client Scripts and Record Producers. We'll examine common challenges, architectural considerations, and implementation strategies that ensure reliable data transfer between client and server components.
Understanding ServiceNow's Data Access Architecture
ServiceNow's data access architecture is built on a multi-layered approach, providing different methods of data interaction depending on the context and requirements. Each layer serves specific purposes and comes with its own set of considerations.
ServiceNow Data Access Methods
1. GlideRecord API
What it's used for: GlideRecord is used for performing CRUD (Create, Read, Update, Delete) operations on ServiceNow tables. This means you can:
Where it's used
GlideRecord is exclusively used in server-side scripts. This includes:
var gr = new GlideRecord('sys_user');
gr.get('sys_id_value'); // Direct access
The most straightforward method for server-side record access. Ideal for:
2. GlideElement
// Accessing field values
current.field_name;
current.reference_field.field_name; // Dot-walking
var gr = new GlideRecord('incident');
if (gr.get('sys_id', 'your_incident_sys_id')) {
var shortDescriptionElement = gr.short_description; // shortDescriptionElement is a GlideElement object
Used for:
3. g_form Client API
Where it's used: g_form is used in client-side scripts only. The most common types are:
// Client Side
g_form.getValue('field_name');
g_form.setValue('field_name', value);
// Client Script (e.g., onChange Client Script on 'category' field)
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (newValue == 'Software') {
g_form.setValue('assignment_group', 'Software Support'); // Set 'assignment_group' field value
} else {
g_form.clearValue('assignment_group'); // Clear 'assignment_group' field value
}
}
// Getting field value
var categoryValue = g_form.getValue('category');
gs.log('Category selected: ' + categoryValue); // gs.log in client-side scripts logs to the browser console
Client-side form manipulation for:
GlideAjax: Bridge Between Client and Server
GlideAjax acts as the communication channel or bridge that allows client-side JavaScript to reach across to the server-side and:
// Server-side (Script Include)
var UserDataHandler = Class.create();
UserDataHandler.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getUserData: function() {
// Server processing
return result;
}
});
// Client-side
var ga = new GlideAjax('UserDataHandler');
ga.addParam('sysparm_name', 'getUserData');
ga.getXMLAnswer(function(answer) {
// Handle response
});
"Blink of an Eye" Speed and Client-Side Updates:
GlideAjax Speed , The "blink of an eye" speed with GlideAjax is achieved because:
Common GlideAjax Challenges and Solutions
1. Data Packaging Issues
Problem:1. String Concatenation Method (Problematic)
var UserDataFetcher = Class.create();
UserDataFetcher.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getUserData: function() {
var grUser = new GlideRecord('sys_user');
if(grUser.get(this.getParameter('sysparm_user_id'))) {
// Problematic: Concatenating multiple values into a string
return grUser.first_name + '|' +
grUser.title + '|' +
grUser.location.name + '|' +
grUser.department.name;
}
return '';
}
});
Technical Challenges in String Concatenation
1.Parsing Architecture Limitations
The delimiter-based parsing approach introduces several technical constraints:
2. System Performance Impact
String concatenation operations affect system performance through:
领英推荐
Why is it called "Problematic" rather than "Wrong"?
It's "problematic" because it works functionally in simple cases. You can get the data to the client using this method. However, it's not the best practice or the most robust, maintainable, or scalable approach, especially when dealing with structured data in web development scenarios like AJAX communication.
Structured Solution Approach
Properly Structured Script Include
The Better Alternative: Using Structured Data (JSON - JavaScript Object Notation):
The preferred and best practice approach in ServiceNow and modern web development for sending data from server-side scripts to client-side scripts (especially via AJAX) is to use JSON (JavaScript Object Notation).
var UserDataFetcher = Class.create();
UserDataFetcher.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getUserData: function() {
try {
var userSysId = this.getParameter('sysparm_user_id');
if (!userSysId) {
return this._createResponse('error', null, 'No user ID provided');
}
var grUser = new GlideRecord('sys_user');
if (!grUser.get(userSysId)) {
return this._createResponse('error', null, 'User not found');
}
// Structured data object
var userData = {
personal: {
first_name: this._getFieldValue(grUser, 'first_name'),
last_name: this._getFieldValue(grUser, 'last_name'),
title: this._getFieldValue(grUser, 'title')
},
organizational: {
department: this._getReferenceValue(grUser, 'department', 'name'),
location: this._getReferenceValue(grUser, 'location', 'name'),
manager: this._getReferenceValue(grUser, 'manager', 'name')
},
system: {
active: this._getFieldValue(grUser, 'active'),
created: this._getFieldValue(grUser, 'sys_created_on')
}
};
return this._createResponse('success', userData, null);
} catch (ex) {
return this._createResponse('error', null, ex.message);
}
},
_getFieldValue: function(gr, fieldName) {
return gr.getValue(fieldName) || '';
},
_getReferenceValue: function(gr, refField, displayField) {
if (gr[refField].nil()) {
return '';
}
return gr[refField][displayField].toString() || '';
},
_createResponse: function(status, data, message) {
return JSON.stringify({
status: status,
data: data,
message: message,
timestamp: new GlideDateTime().getDisplayValue()
});
}
});
Benefits of Using JSON:
2. Reference Field Handling
return grUser.location.name; // May return undefined
// Corrected Approach --
var locationName = '';
if (grUser.location.name) {
? ? locationName = grUser.location.name.toString();
}
Here's what can go wrong:
3.Multiple Field Management
Why the Perception of "Problem" with Multiple Fields and GlideAjax?
The perceived "problem" isn't with GlideAjax's capability, but often with the following implementation issues:
Problematic Approach (Similar to String Concatenation for Single Values): Just as we discussed string concatenation being problematic for single values, it becomes significantly worse when dealing with multiple fields. Developers might try to concatenate multiple field values into a single delimited string to send via GlideAjax. For example:
// Client-side (problematic):
var field1Value = g_form.getValue('field1');
var field2Value = g_form.getValue('field2');
var field3Value = g_form.getValue('field3');
var dataString = field1Value + '|' + field2Value + '|' + field3Value; // Concatenate
var ga = new GlideAjax('MyScriptInclude');
ga.addParam('sysparm_name', 'processMultipleFields');
ga.addParam('sysparm_data', dataString); // Send concatenated string
// ... GlideAjax call ...
// Server-side Script Include (problematic parsing):
processMultipleFields: function() {
var dataString = this.getParameter('sysparm_data');
var values = dataString.split('|'); // Parse back into array
var field1Value = values[0];
var field2Value = values[1];
var field3Value = values[2];
// ... GlideRecord operations using field1Value, field2Value, field3Value ...
}
Why this is problematic for multiple fields:
Error Handling and Recovery
Challenge Description
Error handling in GlideAjax implementations often fails to account for various failure scenarios, leading to poor user experience and system instability.
Technical Impact
Architectural Solutions
A comprehensive error handling strategy should include:
Performance Optimization
Challenge Description
GlideAjax implementations often suffer from performance issues due to inefficient data handling and poor resource utilization.
Technical Impact
Architectural Solutions
Performance optimization requires a multi-faceted approach:
Scalability Considerations
Challenge Description
GlideAjax implementations often face scalability challenges when dealing with increasing data volumes and user loads.
Technical Impact
Architectural Solutions
Ensuring scalability requires:
Conclusion
Successful GlideAjax implementations require careful consideration of these technical challenges and systematic implementation of appropriate solutions. Key recommendations include:
This technical analysis provides a foundation for understanding and addressing common GlideAjax challenges in ServiceNow implementations. Future considerations should include emerging patterns in web services, evolving browser capabilities, and new ServiceNow platform features.
If you want to learn more about this kind of discussion and live training or podcasts then join the Linkedin Group https://bit.ly/SNowRealCaseTraining