i want to make a QR code on the catalog item after selecting two variables named as Asset(List Collector) and User (Lookup Selectbox), and asset refer to cmdb_ci_computer table and user refers sys_user table, my condition is when i select assets and select user then QR will visible on the catalog, and when i select 2 asset and then 1 user then two QR will visible and on scanning the QR i get the asset name , serial number and assigned to as the selected user in the info. i thing for QR type is custom variable and we have to create the widget, provide me the solution for this
Assistant
To achieve the described functionality—displaying dynamic QR codes on a ServiceNow Service Catalog item based on selected assets (cmdb_ci_computer) and user(s) (sys_user)—you need to use a combination of Catalog Client Scripts, Catalog UI Policies (for show/hide logic), and a Custom Variable (likely type: "Label" or "HTML") to render the QR codes. You will also create a custom Service Portal widget or use an external QR code generator JavaScript library to generate QR codes dynamically on the catalog item form.
QR Code variable — Custom Variable (type: HTML or Label) for displaying QR codes
Logic:
When assets and user are selected, generate a QR code for each asset, embedding asset fields + user info.
Implementation:
Use Catalog Client Script (onChange/onSubmit) to detect variable changes.
Use JS QR code library such as QRCode.js clientside to generate QR codes dynamically.
Insert the QR code HTML & info into the QR Code variable.
Visibility:
Show QR Code variable only when assets and user are selected.
Step-by-step Solution
1. Create the variables on the catalog item
Asset: Variable type: List Collector
Table: cmdb_ci_computer
Variable name: asset (example)
User: Variable type: Lookup Select Box
Table: sys_user
Variable name: user
QR Code: Variable type: Label (or HTML)
Variable name: qr_codes
Leave blank initially, will be filled dynamically
2. Include the QRCode.js library in the catalog client script
You can add the QRCode.js library directly in your Catalog Client Script since ServiceNow does not provide it by default. Use a script tag or copy the minified QR code generation library. QRCode.js is a lightweight JS library that generates QR codes in the browser.
You may need to inject this via the Catalog Client Script or use an UI Script if allowed.
3. Create Catalog Client Script
Client script type: onChange (for variables Asset and User)
This script will run when assets or user changes, generates QR codes accordingly.
Here is an example of the script you could use:
javascript
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading) return;
// Get the asset list and user value
var assetVar = g_form.getValue('asset'); // Comma separated sys_ids
var userVar = g_form.getValue('user'); // sys_id of user
// Hide QR Code if no assets or no user selected
if (!assetVar || !userVar) {
g_form.setVisible('qr_codes', false);
return;
}
// Show the QR Code variable container
g_form.setVisible('qr_codes', true);
// Let's fetch the details for the assets and the user via GlideAjax and then render QR codes
fetchDetailsAndRenderQRCodes(assetVar, userVar);
}
function fetchDetailsAndRenderQRCodes(assetSysIds, userSysId) {
var ga = new GlideAjax('QRCodeDataFetcher');
ga.addParam('sysparm_name', 'getAssetUserInfo');
ga.addParam('sysparm_asset_ids', assetSysIds);
ga.addParam('sysparm_user_id', userSysId);
ga.getXMLAnswer(function(response) {
// response will be a JSON string with info array [{assetName, serialNumber, assignedUser}]
var data = JSON.parse(response);
// Now generate QR codes within this container
renderQRCodes(data);
});
}
function renderQRCodes(data) {
var html = '';
// create a div which will hold multiple QR codes
html += '<div id="qr_code_container" style="display:flex;gap:20px;flex-wrap:wrap;">';
data.forEach(function(item, idx){
var qrDivId = 'qrcode_' + idx;
var qrText = 'Asset Name: ' + item.assetName + '\nSerial Number: ' + item.serialNumber + '\nAssigned To: ' + item.assignedUser;
// Each QR code container
html += '<div>';
html += '<div id="'+qrDivId+'"></div>';
html += '<p style="text-align:center;">' + item.assetName + '</p>'
html += '</div>';
});
html += '</div>';
// Insert html - using setValue on label variables doesn't let you set HTML, but usually in catalog client script you can't set innerHTML directly
// Instead use g_form.setValue to set innerHTML of the variable's control or try to access the element directly via jQuery (best)
var container = document.querySelector('#variable_qr_codes');
if (container) {
container.innerHTML = html;
// Now generate QR codes for each qrDiv
data.forEach(function(item, idx){
var qrDivId = 'qrcode_' + idx;
var qrText = 'Asset Name: ' + item.assetName + '\nSerial Number: ' + item.serialNumber + '\nAssigned To: ' + item.assignedUser;
// Create QR code for each item
if (window.QRCode) {
new QRCode(document.getElementById(qrDivId), {
text: qrText,
width: 128,
height: 128
});
}
});
}
}
4. Create a Script Include to fetch Asset and User info
Since the client script cannot query records directly, create a scoped or global Script Include accessible from the client side:
Script Include name: QRCodeDataFetcher
javascript
var QRCodeDataFetcher = Class.create();
QRCodeDataFetcher.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getAssetUserInfo: function() {
var assetIds = this.getParameter('sysparm_asset_ids'); // CSV sys_ids
var userId = this.getParameter('sysparm_user_id');
var userGR = new GlideRecord('sys_user');
if (!userGR.get(userId)) {
return JSON.stringify([]);
}
var assignedUser = userGR.name.toString();
var response = [];
var assetIdArray = assetIds.split(',');
var assetGR = new GlideRecord('cmdb_ci_computer');
assetGR.addQuery('sys_id', 'IN', assetIds);
assetGR.query();
while(assetGR.next()) {
response.push({
assetName: assetGR.getValue('name'),
serialNumber: assetGR.getValue('serial_number'),
assignedUser: assignedUser
});
}
return JSON.stringify(response);
}
});
Make sure this Script Include is Client Callable (checkbox).
5. Adjust the QR Code variable to hidden & show/hide dynamically
By default, set the QR Code variable (qr_codes) to hidden.
Use g_form.setVisible('qr_codes', true/false) to show when conditions are met.
6. Testing
Load the catalog item.
Select one or more assets in the Asset variable.
Select a user in the User variable.
The QR Code variable should appear with QR codes — one QR for each selected Asset.
Each QR code encodes a string like:
code
Asset Name: <name>
Serial Number: <serial number>
Assigned To: <user name>
Scan the QR code to verify the information.
Optional improvements:
Use multi-line QR text formatting for clarity.
Style the QR container and labels for better presentation.
Cache fetched data for performance.
Handle empty serial numbers or missing fields.
Pre-load QRCode.js more elegantly via UI Script or Service Portal widget dependency.
Summary
Step
Purpose
Variables
Collect assets and user info
Client Script
Listen to changes and run logic
Script Include
Fetch asset and user info from DB
QRCode.js lib
Generate QR codes client-side
QR Code variable
Display generated QR codes
This approach uses ServiceNow standard features with minimal server-side overhead and client-side rich UI behavior.
If you want me to provide you a fully packaged solution with exact code files or Service Portal widget instead, just ask!
User
Please clear what is the variable type for qr code and the name of qr variable is qr_code and asset variable name is assets and user is user
Assistant
Thanks for the clarification!
Your variables:
Asset variable name: assets (List Collector)
User variable name: user (Lookup Select Box)
QR Code variable name: qr_code
What should be the variable type for qr_code?
Recommended variable type: Label (or HTML if available, but Label is simpler and supported out-of-the-box)
Why?
Label variables are read-only text or HTML blocks that can be updated dynamically via client script. They do not allow user input, so visual display of the QR codes fits well here.
Important:
When using a Label variable, you cannot set its value with g_form.setValue() in a way that renders HTML automatically.
Instead, you need to fill its container's HTML in client script.
How to target the QR Code variable HTML container?
The container will have an id like: variable_qr_code (prefix variable_ + variable name).
Your client script can manipulate the HTML inside this container like:
js
var container = document.getElementById('variable_qr_code');
if (container) {
container.innerHTML = "<your generated QR codes HTML>";
}
Summary for your case:
Variable Name
Variable Type
Usage
assets
List Collector
Select multiple assets
user
Lookup Select Box
Select one user
qr_code
Label (Read-only)
Place where the dynamic QR codes will be rendered
Sample minimal client script changes using your variable names:
js
User
i created the label type variable, guide me the next steps
Assistant
Great! Now that you have created the qr_code variable as a Label type on your catalog item, here are the next steps to complete the functionality of dynamically generating and displaying QR codes after selecting assets and user.
Step 1: Include QRCode.js Library
The QR code generation requires a JS library like QRCode.js.
Option A: Include via HTML script tag in Catalog Item (recommended for simplicity)
Create a Catalog Client Script (Type: onLoad) to inject the library dynamically:
javascript
function onLoad() {
// Check if QRCode is already loaded
if (typeof QRCode === 'undefined') {
var script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
}
}
Create this onLoad client script for catalog item.
This ensures QRCode.js loads once the form loads.
Step 2: Create Catalog Client Script (onChange) for assets and user
Create a Catalog Client Script of type onChange tied to both variables assets and user.
Script will listen for changes to either variable.
If both variables have value, it will call a GlideAjax to retrieve asset and user info.
Then dynamically render the QR codes inside the qr_code label variable container.
Example client script (replace variable names as per your setup):
javascript
User
create catalog client for onchange of user, and then get the assets variable value and user value for generating the QR, because i can select only 1 variable in onchange so make it based on user
Assistant
Certainly! Since ServiceNow catalog client scripts support onChange on only one variable at a time, we will create an onChange client script on the user variable, then inside that script also get the value of the assets variable, and if both are selected generate the QR codes.
Catalog Client Script onChange (User variable)
Name:Generate QR on User Change
Type: onChange
Variable name:user
Script:
javascript
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading) return;
// Get the values of assets and user
var assetVar = g_form.getValue('assets'); // List Collector CSV sys_ids
var userVar = g_form.getValue('user'); // Sys_id of user
// If either is empty, hide QR code and exit
if (!assetVar || !userVar) {
g_form.setVisible('qr_code', false);
// Also, clear previous qr_code content (optional)
var container = document.getElementById('variable_qr_code');
if (container) container.innerHTML = '';
return;
}
// Show the QR code variable container
g_form.setVisible('qr_code', true);
// Now fetch asset and user info and render QR codes
fetchDetailsAndRenderQRCodes(assetVar, userVar);
}
function fetchDetailsAndRenderQRCodes(assetSysIds, userSysId) {
var ga = new GlideAjax('QRCodeDataFetcher');
ga.addParam('sysparm_name', 'getAssetUserInfo');
ga.addParam('sysparm_asset_ids', assetSysIds);
ga.addParam('sysparm_user_id', userSysId);
ga.getXMLAnswer(function(response) {
var data = JSON.parse(response);
renderQRCodes(data);
});
}
function renderQRCodes(data) {
var html = '<div style="display:flex; gap: 20px; flex-wrap: wrap;">';
data.forEach(function(item, idx) {
var qrDivId = 'qrcode_' + idx;
html += '<div><div id="' + qrDivId + '"></div>';
html += '<p style="margin-top: 5px; text-align: center; max-width: 140px;">' + item.assetName + '</p></div>';
});
html += '</div>';
var container = document.getElementById('variable_qr_code');
if (container) {
container.innerHTML = html;
data.forEach(function(item, idx) {
var qrDivId = 'qrcode_' + idx;
var qrText = 'Asset Name: ' + item.assetName + '\nSerial Number: ' + item.serialNumber + '\nAssigned To: ' + item.assignedUser;
if (typeof QRCode !== 'undefined' && document.getElementById(qrDivId)) {
new QRCode(document.getElementById(qrDivId), {
text: qrText,
width: 128,
height: 128
});
}
});
}
}
User
i select one asset and then select user, but qr code not generated
Assistant
Got it — let's troubleshoot and ensure all parts are correctly configured. Here’s a checklist + some debug tips to identify why the QR codes are not generating when you select one asset and a user.
1. Verify variable names exactly match
assets → List Collector variable (multiple asset sys_ids comma separated)
user → Lookup Select Box variable (single sys_id)
qr_code → Label variable (for QR codes display)
If any variable names do not match these exactly, the script will not find the fields.
2. Make sure QRCode.js library is loaded
You can verify in browser console: Type typeof QRCode and press Enter.
It should return "function" or "object", not"undefined".
If it’s undefined, the script that loads QRCode.js did not run or failed.
Fix:
Create a Catalog Client Script (onLoad) like this:
javascript
function onLoad() {
if (typeof QRCode === 'undefined') {
var script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js';
script.type = 'text/javascript';
script.onload = function() {
console.log('QRCode.js loaded');
};
document.getElementsByTagName('head')[0].appendChild(script);
}
}
3. Make sure Script Include QRCodeDataFetcher exists and is client callable
It must be global (or scoped and client callable).
Verify in Server Logs if any errors occur.
You can test with code snippet on server side:
javascript
var fetcher = new QRCodeDataFetcher();
var result = fetcher.getAssetUserInfo('put_asset_sysid_here', 'put_user_sysid_here');
gs.info(result); // Should print JSON with asset info
4. Add debug logs into the client script's onChange for user
User
it is showing undefined
Assistant
If QRCode is showing as undefined in the browser console, it means the QRCode.js library hasn't loaded properly on your catalog item form/page.
Here's how to fix it step-by-step:
1. Load QRCode.js library properly on your catalog item form
Create a Catalog Client Script (Type = onLoad)
Name: Load QRCode JS library
Applies to your Catalog Item
Script (paste below):
javascript
function onLoad() {
// Check if QRCode library is already loaded
if (typeof QRCode === 'undefined') {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js';
script.onload = function() {
console.log('QRCode.js library loaded');
};
script.onerror = function() {
console.error('Failed to load QRCode.js library');
};
document.getElementsByTagName('head')[0].appendChild(script);
} else {
console.log('QRCode.js library was already loaded');
}
}
Save this client script and test again.
Open browser Console (F12) on the catalog item and reload the page.
Look for the message: QRCode.js library loaded or QRCode.js library was already loaded
Then, type typeof QRCode in the console and press Enter. It should now return "function" or "object", not"undefined".
2. Verify your onChange client script uses QRCode after library is loaded
If your QR code generation function triggers immediately after user changes value, but QRCode.js is not loaded yet, the QRCode constructor will fail.
How to avoid:
Delay QR code generation to run only after QRCode.js library has loaded.
Or ensure that the user makes the selection the library is loaded.
User
still undefined
Assistant
If QRCode is still undefined after adding the onLoad script, it means the script either didn't load or wasn't executed in time. Let's solve this step-by-step.
Best Practice: Include the QRCode.js library as a UI Script in ServiceNow (Recommended)
Step 1: Create a UI Script with QRCode.js
In ServiceNow, go to System UI > UI Scripts.
Click New.
Name it: QRCodeJS
Check Active.
Paste the minified QRCode.js library code inside the script body:
Copy entire contents and paste inside the UI Script (remove <script> tags, paste only JS).
Save.
Because UI Scripts load automatically on forms, you avoid timing or CDN issues.
Step 2: Make sure the UI Script is included on Catalog Item form
UI Scripts by default load globally, so you don't have to do anything else.
The QRCode constructor will be available globally when your catalog item loads.
Step 3: Adjust your client script
Remove your previous onLoad script that tries to inject the library dynamically—it's no longer needed.
Just keep the onChange client script on user variable (and optionally on assets) — your QR generation script will work because QRCode will be defined.
Step 4: Example onChange on user variable
javascript
User
in ui script ; is missing at most of places is it ok
Assistant
Yes, it is perfectly fine that the minified QRCode.js library code in the UI Script has very few or no semicolons (;) and minimal whitespace.
Why?
Minified JavaScript intentionally removes unnecessary spaces, line breaks, and often semicolons, relying on JavaScript's automatic semicolon insertion (ASI) to parse correctly.
The QRCode.js minified version you get from CDN normally has minimal semicolons but still functions correctly.
As long as you paste the library code exactly as provided by the official source (e.g., from cdnjs) into the UI Script (without modification), it will work.
Important:
Do not add or remove semicolons manually unless you know exactly what you're doing.
Just copy the minified code as-is from a trusted source and paste into the UI Script body.
After you create your QRCode.js UI Script and save it active, open your catalog item in the Service Portal or classic UI and open browser console:
js
typeof QRCode
If it returns "function" or "object", the QRCode library has loaded fine and semicolon usage is not a problem.
In summary:
Lack of semicolons in minified third-party scripts like QRCode.js is normal and expected, and is not a problem at all. Just use the official minified version as-is.
Let me know if you want me to provide the exact minified QRCode.js you can paste!
User
v
Assistant
It seems your last message was just "v". Could you please clarify or provide more details on what you need help with? I'm here to assist!
User
ErrorThere is a JavaScript error in your browser console
Assistant
A JavaScript error in the browser console could be caused by several things in your ServiceNow catalog item setup, especially related to the QR code generation steps we've discussed. To help you fix this, here’s a systematic approach:
Step 1: Identify the exact error message
Open your browser’s developer console (F12 or Ctrl+Shift+I).
Go to the Console tab.
Look for the red error message(s).
Copy the full error message, including line number and stack trace if available.
Common errors could be:
ReferenceError: QRCode is not defined
TypeError: document.getElementById(...) is null
Syntax errors or other issues.
Step 2: Common fixes based on typical errors
2.1. If error: QRCode is not defined
Cause: QRCode.js library is not loaded.
Fix:
Ensure you created and activated the UI Script with QRCode.js code.
Remove any onLoad scripts trying to load QRCode.js dynamically (avoid duplicates).
Verify library loaded by typing typeof QRCode in console (should return "function" or "object").
2.2. If error: Cannot read property 'innerHTML' of null or similar
Cause: The container element for the QR code variable does not exist in DOM yet.
Fix:
Make sure your variable name is correct (qr_code).
Inspect the page and confirm the element ID for the label variable container is variable_qr_code (sometimes variable prefix differs, confirm via DOM inspector).
Add a small delay or ensure your script runs after the DOM is ready.
2.3. If error: SyntaxError
Usually indicates malformed JavaScript code. Check your client scripts for any missing brackets, commas, or unclosed strings.
Step 3: Provide a minimal working example for your onChange Client Script on user
Replace your current onChange script with this tested sample (adjust variable names if needed):
javascript
User
type of QR return undefined
Assistant
If typeof QRCode returns undefined, it means the QRCode.js library is not loaded on your page. To fix this reliably, follow these steps to properly include QRCode.js in your ServiceNow instance and ensure it is available for your client scripts:
Step 1: Add QRCode.js as a UI Script in ServiceNow (Recommended Way)
Important: Paste only the JavaScript code—no <script> tags.
Save the UI Script.
UI Scripts load automatically in ServiceNow and are available globally if active.
Step 2: Remove any dynamic QRCode.js injections
Remove any Catalog Client Script that dynamically loads QRCode.js from CDN.
This avoids race conditions where your script runs before the library is loaded.
Step 3: Confirm QRCode.js is loaded on the page
Open your catalog item form.
Open browser console (press F12).
Type:
javascript
typeof QRCode
If it returns "function" or "object", the library is loaded correctly.
If still "undefined", clear your browser cache & reload.
Step 4: Now use your existing client script to generate QR codes
Since QRCode.js is loaded globally, your QR code generation code will work without modification.
Optional: Quick test snippet you can paste in browser console to test QRCode
javascript
var div = document.createElement('div');
document.body.appendChild(div);
new QRCode(div, {
text: "Test QR Code",
width: 128,
height: 128
});
If you see a QR code on the page, it confirms QRCode.js is loaded properly.
Summary:
Step
Action
UI Script QRCodeJS
Created and active with QRCode.js
Remove CDN injection
Avoid loading QRCode.js multiple times
Confirm loaded
typeof QRCode returns function
Use client scripts
Generate QR codes as previously provided
If you want me to provide the complete minified code of QRCode.js ready to paste into UI Script, just ask!
User
not showing and still undefined, please consider it from different scenerio like widget or etc
Assistant
Since loading the QRCode.js library via UI Script or dynamic script injection is not working in your environment and QRCode remains undefined, the most reliable and modern approach in ServiceNow is to handle this via a Service Portal widget where you have full control over client-side dependencies, including loading external libraries.
Solution: Use a Service Portal Widget to generate QR codes dynamically for your Catalog Item
You can create a widget that:
Loads QRCode.js via the widget's client dependencies
Reacts to variable changes (user and assets)
Displays one QR code per asset with user info embedded
Overview of Steps
Create a Service Portal Widget (Scoped App) for QR Code rendering
Add QRCode.js as a widget client dependency
Expose variables (assets and user) to the widget
Render QR code(s) dynamically when variables change
Embed the widget in your Catalog Item form or Service Portal Catalog page
Detailed Instructions
1. Create the Widget
In Studio, create a new widget, e.g., catalog-item-qr-codes.
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading) return;
var assetVar = g_form.getValue('assets'); // list collector: CSV of sys_ids
var userVar = g_form.getValue('user');
if (!assetVar || !userVar) {
g_form.setVisible('qr_code', false);
return;
}
g_form.setVisible('qr_code', true);
fetchDetailsAndRenderQRCodes(assetVar, userVar);
}
function fetchDetailsAndRenderQRCodes(assetSysIds, userSysId) {
var ga = new GlideAjax('QRCodeDataFetcher');
ga.addParam('sysparm_name', 'getAssetUserInfo');
ga.addParam('sysparm_asset_ids', assetSysIds);
ga.addParam('sysparm_user_id', userSysId);
ga.getXMLAnswer(function(response) {
var data = JSON.parse(response);
renderQRCodes(data);
});
}
function renderQRCodes(data) {
var html = '<div style="display:flex;gap:20px;flex-wrap:wrap;">';
data.forEach(function(item, idx){
var qrDivId = 'qrcode_' + idx;
html += '<div><div id="' + qrDivId + '"></div>';
html += '<p style="text-align:center;">' + item.assetName + '</p></div>';
});
html += '</div>';
var container = document.getElementById('variable_qr_code');
if (container) {
container.innerHTML = html;
data.forEach(function(item, idx){
var qrDivId = 'qrcode_' + idx;
var qrText = 'Asset Name: ' + item.assetName + '\nSerial Number: ' + item.serialNumber + '\nAssigned To: ' + item.assignedUser;
if (window.QRCode) {
new QRCode(document.getElementById(qrDivId), {
text: qrText,
width: 128,
height: 128
});
}
});
}
}
Make sure:
Your QRCode.js library is included on the page (e.g. via <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>)
Your Script Include QRCodeDataFetcher includes the method getAssetUserInfo (as per earlier instructions).
The QR Code variable (qr_code) is initially hidden and only shown when both assets and user are selected.
If you want me to help with the full code snippet including Script Include or how to add QRCode.js, just say!
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading) return;
var assetVar = g_form.getValue('assets'); // List collector - CSV sys_ids
var userVar = g_form.getValue('user'); // Lookup user
// Hide QR Code variable if no selection
if (!assetVar || !userVar) {
g_form.setVisible('qr_code', false);
return;
}
// Show QR Code variable & generate codes
g_form.setVisible('qr_code', true);
fetchDetailsAndRenderQRCodes(assetVar, userVar);
}
function fetchDetailsAndRenderQRCodes(assetSysIds, userSysId) {
var ga = new GlideAjax('QRCodeDataFetcher');
ga.addParam('sysparm_name', 'getAssetUserInfo');
ga.addParam('sysparm_asset_ids', assetSysIds);
ga.addParam('sysparm_user_id', userSysId);
ga.getXMLAnswer(function(response) {
var data = JSON.parse(response);
renderQRCodes(data);
});
}
function renderQRCodes(data) {
var html = '<div style="display:flex;gap:20px;flex-wrap:wrap;">';
data.forEach(function(item, idx){
var qrDivId = 'qrcode_' + idx;
html += '<div><div id="' + qrDivId + '"></div>';
html += '<p style="text-align:center;max-width:140px;">' + item.assetName + '</p></div>';
});
html += '</div>';
var container = document.getElementById('variable_qr_code');
if (container) {
container.innerHTML = html;
data.forEach(function(item, idx){
var qrDivId = 'qrcode_' + idx;
var qrText = 'Asset Name: ' + item.assetName + '\nSerial Number: ' + item.serialNumber + '\nAssigned To: ' + item.assignedUser;
if (typeof QRCode !== 'undefined' && document.getElementById(qrDivId)) {
new QRCode(document.getElementById(qrDivId), {
text: qrText,
width: 128,
height: 128
});
}
});
}
}
Step 3: Create the Script Include QRCodeDataFetcher
Create a Script Include named QRCodeDataFetcher (check the "Client Callable" box).
Paste the following code:
javascript
var QRCodeDataFetcher = Class.create();
QRCodeDataFetcher.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getAssetUserInfo: function() {
var assetIds = this.getParameter('sysparm_asset_ids'); // CSV sys_ids
var userId = this.getParameter('sysparm_user_id');
var userGR = new GlideRecord('sys_user');
if (!userGR.get(userId)) {
return JSON.stringify([]);
}
var assignedUser = userGR.getValue('name');
var response = [];
var assetGR = new GlideRecord('cmdb_ci_computer');
assetGR.addQuery('sys_id', 'IN', assetIds);
assetGR.query();
while (assetGR.next()) {
response.push({
assetName: assetGR.getValue('name'),
serialNumber: assetGR.getValue('serial_number'),
assignedUser: assignedUser
});
}
return JSON.stringify(response);
}
});
Step 4: Set Initial Visibility of qr_code variable to Hidden
In the catalog item form, set the qr_code variable to Hidden by default.
It will be shown programmatically when proper variables are selected.
Step 5: Test the Catalog Item
Open the catalog item form.
On load, QRCode.js library should inject.
Select 1 or more assets in the assets list collector.
Select a user in the user variable.
The qr_code label variable should appear and show one QR code per asset.
Each QR code encodes the asset name, serial number, and the assigned user.
Scan the QR code with a QR scanner to verify the data encoded.
Troubleshooting Tips
Use browser dev tools console to check for any JS errors.
Confirm QRCode.js library is loaded before client script runs.
Confirm Script Include name and client callable checkbox.
Make sure variable names are exactly as you defined (assets, user, qr_code).
Inspect the qr_code container element in the DOM to check if the QR codes are rendered.
If you want me to provide you with the full script files ready-to-paste for your catalog item, just ask!
Important Notes:
Make sure:
You have the QRCode.js library loaded on the catalog item page (e.g., via onLoad client script injecting the CDN).
The variable name of your assets list collector is exactly assets.
The variable name of your user lookup select box is exactly user.
The QR code variable name is qr_code and it is of type Label (hidden on load).
The Script Include QRCodeDataFetcher exists and is client callable, as described earlier.
This script only runs when user variable changes, but it reads the selected assets variable value at that time.
If you want to regenerate the QR codes also when the assets variable changes, you need a similar onChange script on the assets variable as well, with the same code but with user and assets values switched:
javascript
// Similar catalog onChange for assets variable:
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading) return;
var assetVar = g_form.getValue('assets');
var userVar = g_form.getValue('user');
if (!assetVar || !userVar) {
g_form.setVisible('qr_code', false);
var container = document.getElementById('variable_qr_code');
if (container) container.innerHTML = '';
return;
}
g_form.setVisible('qr_code', true);
fetchDetailsAndRenderQRCodes(assetVar, userVar);
}
// reuse fetchDetailsAndRenderQRCodes and renderQRCodes functions same as above
If you want, I can help generate that second client script too.
Let me know if you want me to package these scripts as ready-to-copy or help with any further setup!
Modify your client script for quick debugging:
javascript
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading) return;
var assetVar = g_form.getValue('assets');
var userVar = g_form.getValue('user');
console.log('Assets:', assetVar);
console.log('User:', userVar);
if (!assetVar || !userVar) {
console.log('Either assets or user are not selected; hiding qr_code');
g_form.setVisible('qr_code', false);
var container = document.getElementById('variable_qr_code');
if (container) container.innerHTML = '';
return;
}
g_form.setVisible('qr_code', true);
fetchDetailsAndRenderQRCodes(assetVar, userVar);
}
Open browser console and confirm these logs output as expected when you change variables.
5. Confirm you have a similar onChange client script on assets variable (optional, but best)
QR will only update when user variable changes, so if you select assets first and then user, it will generate. But if you select user first and then assets, qr_code won't generate until user is changed again.
Best to have both onChange client scripts for user and assets. You can reuse the same code in both.
6. Manually test GlideAjax call from browser console (advanced)
Open browser console and try:
javascript
var ga = new GlideAjax('QRCodeDataFetcher');
ga.addParam('sysparm_name', 'getAssetUserInfo');
ga.addParam('sysparm_asset_ids', 'SYS_ID_OF_YOUR_SELECTED_ASSET'); // replace with actual asset sys_id
ga.addParam('sysparm_user_id', 'SYS_ID_OF_YOUR_SELECTED_USER'); // replace with actual user sys_id
ga.getXMLAnswer(function(response){
console.log('AJAX response:', response);
});
Replace the SYS_ID with real chosen values (you can get sys_ids by inspecting variables or via debugging tools).
Check if you get a valid JSON response.
7. Add safety check for empty or erroneous GlideAjax result
In fetchDetailsAndRenderQRCodes function, add:
javascript
if (!response || response.length === 0) {
var container = document.getElementById('variable_qr_code');
if (container) container.innerHTML = '<p>No asset info found.</p>';
return;
}
8. Check for any JavaScript errors
Open browser console and reload form. Look for JS errors which might stop execution.
Recap: minimum working configuration
Label type variable: qr_code (hidden by default)
List Collector variable: assets
Lookup variable: user
onChange script on user (and preferably on assets) calling the QR generation code
Script Include QRCodeDataFetcher with proper function to return JSON
QRCode.js loaded on the page
If after checking these steps you still face issues, please share:
Your exact client script code for onChange on user
How you are loading QRCode.js
Script Include code
Any errors from browser console or system logs
I will help you debug step-by-step.
Feel free to share details!
after
3. Optional: Add a wait/retry mechanism before generating QR codes
Modify your renderQRCodes function to wait for QRCode.js if not ready:
javascript
function renderQRCodes(data) {
var html = '<div style="display:flex; gap: 20px; flex-wrap: wrap;">';
data.forEach(function(item, idx) {
var qrDivId = 'qrcode_' + idx;
html += '<div><div id="' + qrDivId + '"></div>';
html += '<p style="margin-top: 5px; text-align: center; max-width: 140px;">' + item.assetName + '</p></div>';
});
html += '</div>';
var container = document.getElementById('variable_qr_code');
if (container) {
container.innerHTML = html;
// Helper to generate QR after confirming QRCode.js is loaded
function generateQRCodes() {
if (typeof QRCode === 'undefined') {
// Retry after 100ms if not loaded yet
setTimeout(generateQRCodes, 100);
return;
}
data.forEach(function(item, idx) {
var qrDivId = 'qrcode_' + idx;
var qrText = 'Asset Name: ' + item.assetName + '\nSerial Number: ' + item.serialNumber + '\nAssigned To: ' + item.assignedUser;
if (document.getElementById(qrDivId)) {
new QRCode(document.getElementById(qrDivId), {
text: qrText,
width: 128,
height: 128
});
}
});
}
generateQRCodes();
}
}
4. Test full flow
Reload the catalog item form page.
Open browser console (F12 → Console).
Verify you see your QRCode.js library loaded log.
Select asset(s) and then user (or vice versa).
QR codes should generate under your qr_code label variable.
If you want me to review or provide a full package of working scripts including Script Include, Client Scripts (onLoad, onChange), I can provide that too. Just say!
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading) return;
var assetVar = g_form.getValue('assets');
var userVar = g_form.getValue('user');
if (!assetVar || !userVar) {
g_form.setVisible('qr_code', false);
var container = document.getElementById('variable_qr_code');
if (container) container.innerHTML = '';
return;
}
g_form.setVisible('qr_code', true);
fetchDetailsAndRenderQRCodes(assetVar, userVar);
}
function fetchDetailsAndRenderQRCodes(assetSysIds, userSysId) {
var ga = new GlideAjax('QRCodeDataFetcher');
ga.addParam('sysparm_name', 'getAssetUserInfo');
ga.addParam('sysparm_asset_ids', assetSysIds);
ga.addParam('sysparm_user_id', userSysId);
ga.getXMLAnswer(function(response) {
var data = JSON.parse(response);
renderQRCodes(data);
});
}
function renderQRCodes(data) {
var html = '<div style="display:flex; gap: 20px; flex-wrap: wrap;">';
data.forEach(function(item, idx) {
var qrDivId = 'qrcode_' + idx;
html += '<div><div id="' + qrDivId + '"></div>';
html += '<p style="margin-top: 5px; text-align: center; max-width: 140px;">' + item.assetName + '</p></div>';
});
html += '</div>';
var container = document.getElementById('variable_qr_code');
if (container) {
container.innerHTML = html;
data.forEach(function(item, idx) {
var qrDivId = 'qrcode_' + idx;
var qrText = 'Asset Name: ' + item.assetName + '\nSerial Number: ' + item.serialNumber + '\nAssigned To: ' + item.assignedUser;
if (document.getElementById(qrDivId)) {
new QRCode(document.getElementById(qrDivId), {
text: qrText,
width: 128,
height: 128
});
}
});
}
}
Step 5: Test
Reload your catalog item form.
Confirm in browser console: typeof QRCode --> should return "function" or "object" (not "undefined").
Select asset(s) and user.
The QR codes should be generated and displayed inside the qr_code label variable.
Summary checklist:
Step
Done?
Notes
Created UI Script with QRCode.js
✔️
Copy-paste full QRCode.js code
Removed dynamic script load
✔️
Avoid double loading or timing issues
Client Script onChange on user
✔️
Use above code
qr_code variable is Label type
✔️
Initially hidden
QRCodeDataFetcher Script Include
✔️
Returns asset and user info JSON
If you want, I can provide you the minified QRCode.js library code to paste directly into UI Script.
Let me know if you want me to help with the full ready-to-import code package!
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading) return;
var assetVar = g_form.getValue('assets');
var userVar = g_form.getValue('user');
if (!assetVar || !userVar) {
g_form.setVisible('qr_code', false);
var container = document.getElementById('variable_qr_code');
if (container) container.innerHTML = '';
return;
}
g_form.setVisible('qr_code', true);
fetchDetailsAndRenderQRCodes(assetVar, userVar);
}
function fetchDetailsAndRenderQRCodes(assetSysIds, userSysId) {
var ga = new GlideAjax('QRCodeDataFetcher');
ga.addParam('sysparm_name', 'getAssetUserInfo');
ga.addParam('sysparm_asset_ids', assetSysIds);
ga.addParam('sysparm_user_id', userSysId);
ga.getXMLAnswer(function(response) {
try {
var data = JSON.parse(response);
renderQRCodes(data);
} catch (e) {
console.error('Failed to parse GlideAjax response:', e);
}
});
}
function renderQRCodes(data) {
var container = document.getElementById('variable_qr_code');
if (!container) {
console.error('QR code container element not found');
return;
}
if (!data || data.length === 0) {
container.innerHTML = '<p>No data available to generate QR codes.</p>';
return;
}
var html = '<div style="display:flex; gap: 20px; flex-wrap: wrap;">';
data.forEach(function(item, idx) {
var qrDivId = 'qrcode_' + idx;
html += '<div><div id="' + qrDivId + '"></div>';
html += '<p style="margin-top: 5px; text-align: center; max-width: 140px;">' + item.assetName + '</p></div>';
});
html += '</div>';
container.innerHTML = html;
if (typeof QRCode === 'undefined') {
console.error('QRCode library is not loaded');
return;
}
data.forEach(function(item, idx) {
var qrDivId = 'qrcode_' + idx;
var qrText = 'Asset Name: ' + item.assetName + '\nSerial Number: ' +
item.serialNumber + '\nAssigned To: ' + item.assignedUser;
new QRCode(document.getElementById(qrDivId), {
text: qrText,
width: 128,
height: 128
});
});
}
Step 4: Check your Script Include QRCodeDataFetcher
Make sure it’s marked Client Callable and the server-side logic matches what your client script expects:
javascript
var QRCodeDataFetcher = Class.create();
QRCodeDataFetcher.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getAssetUserInfo: function() {
var assetIds = this.getParameter('sysparm_asset_ids'); // CSV sys_ids
var userId = this.getParameter('sysparm_user_id');
var userGR = new GlideRecord('sys_user');
if (!userGR.get(userId)) {
return JSON.stringify([]);
}
var assignedUser = userGR.getValue('name');
var response = [];
var assetGR = new GlideRecord('cmdb_ci_computer');
assetGR.addQuery('sys_id', 'IN', assetIds);
assetGR.query();
while (assetGR.next()) {
response.push({
assetName: assetGR.getValue('name'),
serialNumber: assetGR.getValue('serial_number'),
assignedUser: assignedUser
});
}
return JSON.stringify(response);
}
});
Step 5: Reply with exact error message
If you still get errors, please:
Copy-paste the full error message from the browser console.
Share which part (client script, Script Include, browser console) the error points to.
Share which browser and ServiceNow UI you're using (classic, Service Portal, etc.).
I’m here to help troubleshoot further once you provide the error details!
(function() {
var ctrl = this;
ctrl.$onInit = function() {
ctrl.qrInstances = [];
// Watch assets and user data
ctrl.$scope.$watchGroup(['c.data.assets', 'c.data.user'], function(newVal) {
if (newVal && newVal[0].length && newVal[1]) {
ctrl.renderQRCodes();
} else {
ctrl.clearQRCodes();
}
});
};
ctrl.renderQRCodes = function() {
ctrl.clearQRCodes();
ctrl.data.assets.forEach(function(asset, idx){
var qrDivId = 'qrcode_' + idx;
var qrText = "Asset Name: " + asset.name + "\nSerial Number: " + asset.serial_number + "\nAssigned To: " + ctrl.data.user.name;
var qrDiv = document.getElementById(qrDivId);
if (qrDiv && QRCode) {
var qr = new QRCode(qrDiv, {
text: qrText,
width: 128,
height: 128
});
ctrl.qrInstances.push(qr);
}
});
};
ctrl.clearQRCodes = function() {
ctrl.qrInstances.forEach(function(qr) {
// QRCode.js does not provide direct removal, so clear html container
if (qr._el) {
qr._el.innerHTML = '';
}
});
ctrl.qrInstances = [];
};
})();
widget.server.js
js
(function() {
// Server side: receive sys_ids of assets and user then fetch their details
var assetIds = options.assets || [];
var userId = options.user || "";
var data = {
assets: [],
user: null
};
if (userId) {
var userGR = new GlideRecord('sys_user');
if (userGR.get(userId)) {
data.user = {
sys_id: userGR.getValue('sys_id'),
name: userGR.getValue('name')
};
}
}
if (assetIds.length) {
var assetGR = new GlideRecord('cmdb_ci_computer');
assetGR.addQuery('sys_id', 'IN', assetIds);
assetGR.query();
while(assetGR.next()) {
data.assets.push({
sys_id: assetGR.getValue('sys_id'),
name: assetGR.getValue('name'),
serial_number: assetGR.getValue('serial_number')
});
}
}
return data;
})();
2. Add QRCode.js Dependency in widget's Client Script Includes
In widget configuration panel’s Client Script Includes or Libraries add: