Client Scripts
Debounced Search with GlideAjax
Implement a debounced search to avoid excessive server calls when users type in a search field, improving performance.
// Global variable to store timeout (outside function)
var searchTimeout;
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
// Exit if form is loading
if (isLoading) {
return;
}
// Configuration
var debounceDelay = 500; // Wait 500ms after user stops typing
var minSearchLength = 3; // Minimum characters before searching
var resultsField = 'u_search_results'; // Field to display results
// Clear any existing timeout
if (searchTimeout) {
clearTimeout(searchTimeout);
}
// Clear results if search is too short
if (!newValue || newValue.length < minSearchLength) {
g_form.clearValue(resultsField);
g_form.hideFieldMsg(resultsField);
return;
}
// Show searching indicator
g_form.showFieldMsg(resultsField, 'Searching...', 'info', false);
// Set new timeout to execute search after delay
searchTimeout = setTimeout(function() {
// Make GlideAjax call to search
var ga = new GlideAjax('SearchUtils'); // Create corresponding Script Include
ga.addParam('sysparm_name', 'performSearch');
ga.addParam('sysparm_search_term', newValue);
ga.addParam('sysparm_search_table', 'cmdb_ci'); // Table to search
ga.addParam('sysparm_search_fields', 'name,serial_number'); // Fields to search
ga.getXMLAnswer(function(response) {
if (response) {
try {
var results = JSON.parse(response);
// Clear previous message
g_form.hideFieldMsg(resultsField);
if (results.count > 0) {
// Display results count
var message = 'Found ' + results.count + ' matching record(s)';
g_form.showFieldMsg(resultsField, message, 'info');
// Optionally populate a reference field with first result
if (results.records && results.records.length > 0) {
var firstResult = results.records[0];
// g_form.setValue('u_related_ci', firstResult.sys_id);
}
// Store results in hidden field or display in custom way
g_form.setValue(resultsField, JSON.stringify(results.records));
} else {
g_form.showFieldMsg(resultsField, 'No matching records found', 'warning');
g_form.clearValue(resultsField);
}
} catch (e) {
g_form.showFieldMsg(resultsField, 'Error parsing search results', 'error');
console.error('Search error:', e);
}
} else {
g_form.showFieldMsg(resultsField, 'Search failed - no response', 'error');
}
});
}, debounceDelay);
}How to use it
1. Create an onChange Client Script on your search field 2. Create a Script Include named 'SearchUtils' with 'performSearch' function 3. Adjust debounceDelay and minSearchLength for your needs 4. Customize the search table and fields 5. Update resultsField to match your form 6. Test by typing quickly - should only trigger after pause 7. Monitor server logs to confirm reduced call frequency
Adapt the table names, fields, and conditions to your instance. Test the behavior in a development environment before using it in production.