Get a first look at what's coming. The Developer Passport Australia Release Preview kicks off March 12. Dive in! 

How to use GlideAjax?

ayushaggarw
Giga Contributor

I have a task - 
When a user selects a Caller on an Incident form, the system should fetch the caller's department from the server
and populate a custom field on the form without reloading the page. Design the solution using a client callable
Script Include and a client script.


Conditions / expectations:
• Do not hardcode department values in the client script.
• Use GlideAjax for communication.
• Handle the case where the user has no department.
Success criteria: A working client-side interaction where the department is fetched from the server and populated
correctly.

I created column in incident table and create client script and script include and select the user with department but it does not autofill in the incident table why anyone help me out of this?

5 REPLIES 5

Its_Sagnic
Giga Guru

Hi @ayushaggarw ,

Hope you are doing well.

Try to use the below code snippets.

1. The Script Include : 

  • Step 1: You must check the "Client callable" box.
  • Step 2: 
var UserDetailsUtils = Class.create();
UserDetailsUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, { // Connects to the Ajax system

    getDept: function() {
        // 1. Get the User ID 
        var userId = this.getParameter('sysparm_user_id');
        
        // 2. Look up the User record in the database
        var userGR = new GlideRecord('sys_user');
        if (userGR.get(userId)) {
            // 3. Get the "Department" name
            var department = userGR.getDisplayValue('department');
            
            // 4. Return it, or a message if empty 
            return department ? department : "No Department Assigned";
        }
        return "";
    },

    type: 'UserDetailsUtils'
});
  •  Step 3The Client Script
         Type : onChange
         Field name: Caller
  • Step 4 :
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        g_form.setValue('u_caller_department', ''); // Clear your custom field
        return;
    }

    // 1. Start the "GlideAjax" request
    var ga = new GlideAjax('UserDetailsUtils'); // Name of the Script Include
    ga.addParam('sysparm_name', 'getDept');      // Name of the function to run
    ga.addParam('sysparm_user_id', newValue);    // Pass the new Caller's sys_id

    // 2. Send the request and wait for the "answer" (getXMLAnswer is the modern way)
    ga.getXMLAnswer(function(answer) {
        if (answer) {
            // 3. Populate your custom field with the result 
            g_form.setValue('u_caller_department', answer);
        }
    });
}


Use the above code to get your solution. If you find it helpful for you please mark it as helpful.

Regards,

Sagnic