Monday, 10 December 2018

Client-Server call in ServiceNow / Ajax Call / Asynchronous Call

AJAX (asynchronous JavaScript and XML) is a group of interrelated, client-side development techniques used to create asynchronous Web applications.
AJAX enables web applications to send and retrieve information to and from a server in the background, without impacting the user experience with the displayed web page.


GlideAjax:


The GlideAjax class allows the execution of server-side code from the client. GlideAjaxcalls pass parameters to the script includes, and, using naming conventions, allows the use of these parameters.

Using GlideAjax:
·         Initialize GlideAjax with the name of the script include that you want to use.
·         When creating the script include, you must set the name field to be exactly the same as the class name.
·         When creating the script include, you must select the Client callable check box.
·         Specify the parameter sysparm_name. GlideAjax uses sysparm_name to find which function to use.
·         Any extra parameters may be passed in, all of which must begin with sysparm_. Avoid using predefined parameter names:
o   sysparm_name
o   sysparm_function
o   sysparm_value
o   sysparm_type
·         Code is then executed with the getXML() or getXMLWait() functions.



Example of asynchronous GlideAjax call
Client Side:
var ga = new GlideAjax('HelloWorld');
ga.addParam('sysparm_name', 'helloWorld');
ga.addParam('sysparm_user_name', "Bob");
ga.getXML(HelloWorldParse);
 
function HelloWorldParse(response) {
  var answer = response.responseXML.documentElement.getAttribute("answer");
  alert(answer); }

Server Side Code:
var HelloWorld = Class.create();
HelloWorld.prototype = Object.extendsObject(AbstractAjaxProcessor, {
   helloWorld:function() { return "Hello " + this.getParameter('sysparm_user_name') + "!"; } ,
   _privateFunction: function() { // this function is not client callable     
    }
 });


Note: You must set the name of the script include to HelloWorld.
  • ·         The sys_script_include code must extend the AbstractAjaxProcessorclass and be client-callable.
  • ·         Function names starting with "_" are considered private and are not callable from the client.
  • ·         Avoid overriding methods of AbstractAjaxProcessor, including initialize. While it is possible to invoke methods of your superclass object which you have overridden, it is complicated and best avoided altogether.




No comments:

Post a comment