The problem

Script Includes in ServiceNow, in a very simplistic explanation, is a server side script that can be called from other server scripts, making them great for re-usability.

Client callable script includes in ServiceNow are typically combined with an ServiceNow API method called GlideAjax. It’s a method that handles the actual AJAX part of your script that sends and receives data between the client and the server.

Often, it’s easier to think of these things separately, but for ease of use, there’s often times we’d want to combine them.

Click here to jump straight to the solution

Example of Server Callable Script Includes

Script Include:

var My_Functions = Class.create();
My_Functions.prototype = {
    initialize: function() {
    },

	log_info: function(x) {
		gs.info(x);
		return 'success';
	},
	
    type: 'My_Functions'
};


Code that calls script include function:

var y = new My_Functions().log_info('Testing');
  • y would be set to ‘success’
  • ‘Testing’ would be logged to the system (via gs.info())

Example of Client Callable Script Includes

Script Include (Set Client callable to true):

var My_Functions = Class.create();
My_Functions.prototype = Object.extendsObject(AbstractAjaxProcessor, {
	log_info: function(){
		var results = {};
		var x = this.getParameter('sysparm_x');
		gs.info(x);
		results.message = 'success';
		return JSON.stringify(results);
	},
	
    type: 'My_Functions'
});


Code that calls the script include function:

function onChange(control, oldValue, newValue, isLoading) {
	if (isLoading || newValue == '') {
		return;
	}

	var ga = new GlideAjax('My_Functions'); 
	ga.addParam('sysparm_name','log_info'); 
	ga.addParam('sysparm_x', 'Testing'); 
	ga.getXML(ResponseFunction); 
	
	function ResponseFunction(response) { 
		var answer = response.responseXML.documentElement.getAttribute("answer"); 
		var results = JSON.parse(answer);
		alert(results.message);
	}
}
  • An alert window would appear with the value of results.message which would be ‘success’
  • ‘Testing’ would be logged to the system (via gs.info())

Example of a single combined Script include

Script include (note the small changes in bold from the example client-callable script include):

var My_Functions = Class.create();
My_Functions.prototype = Object.extendsObject(AbstractAjaxProcessor, {
	log_info: function(x0){
		var results = {};
		var x = this.getParameter('sysparm_x') || x0;
		gs.info(x);
		results.message = 'success';
		return JSON.stringify(results);
	},
	
    type: 'My_Functions'
});


Because of the small changes:

  • When called from client, it still sets x according to the .getParameter() function
  • When called from server, if passed a parameter, it first passes to the function then gets set to x because of the lack of parameters to retrieve.

Presto, a single function with parameters that can now be called either way.