How to merge two GlideAjax calls onLoad into one

matthew_hughes
Kilo Sage

I've got two functions within my script include:

retrieveGroupWideField: function() {

        //Setup the parameter for the selected Business Application
        var busApp = this.getParameter('sysparm_app');

        //Setup the boolean variable for checking if the selected Business Application is consumed group wide
        var gw_Check = false;

        //Setup the variable to pass the outcome of gw_check to the client script
        var result = this.newItem("result");

        //Check if there are any entries in the 'M2m Depts Config Items' table with the selected Business Application
        var grBusinessApp = new GlideRecord('cmdb_ci_business_app');
        grBusinessApp.get(busApp);

        //Assign the value of the 'Consumed Group Wide' field to the 'gw_Check' variable
        gw_Check = grBusinessApp.u_consumed_group_wide;

        //Set the 'gw_Check' attribute to be the value of the 'gw_Check' variable
        result.setAttribute('gw_Check', gw_Check);

    },
 
existingConsumerOrgs: function() {

        //Setup the parameter for the selected Business Application
        var busApp = this.getParameter('sysparm_app');

        //Setup the array for returning the list of entries in the 'M2m Depts Config Items' table related to the Business Applicaiton
        var dept_data = [];

        //Setup the object to check for any departments related to the Business Application that have already been seen
        var viewedDepartments = {};

        //GlideRecord query to check if there are any entries in the 'M2m Depts Config Items' table with the selected Business Application
        var grConsumerRecordEntries = new GlideRecord('u_m2m_depts_config_items');
        grConsumerRecordEntries.addQuery('u_configuration_item', busApp);
        grConsumerRecordEntries.addNotNullQuery('u_department');
        grConsumerRecordEntries.query();

        //whilst grConsumerRecordEntries is looking for records
        while (grConsumerRecordEntries.next()) {

            //Get the Sys ID of the current Department
            var departmentSysId = grConsumerRecordEntries.getValue('u_department');

            //If the current Department has already been seen, we carry on
            if (viewedDepartments[departmentSysId]) {
                continue;
            }

            //Set the boolean value to true for each Department that is seen
            viewedDepartments[departmentSysId] = true;

            //Retrieve the value of the 'ID' field of the department record
            var grDepartmentRecord = new GlideRecord('cmn_department');
            grDepartmentRecord.get(departmentSysId);

            //Set the variable to assign the 'ID' value of the current Department
            var departmentID = grDepartmentRecord.getValue('id');

            //Setup the variable to get the parent of the current Department record
            var parent = grDepartmentRecord.getValue('parent');


            //Setup the variable to pass the value of the Business Unit/Function. If there is a parent record and it has a Department Type of Business Unit/Function or has the 'Is Business Unit' set to true, set that in the 'businessUnitFunction' variable. Otherwise, pass in the Sys ID of the current Department record
            var businessUnitFunction;

            if (parent) {
                var grParentTypeCheck = new GlideRecord('cmn_department');
                if (grParentTypeCheck.get(parent)) {
                    var parentDepartmentType = grParentTypeCheck.getValue('u_department_type');
                    var parentIsBusinessUnit = grParentTypeCheck.getValue('u_business_unit') == 'true';

                    if (parentDepartmentType == 'Business Unit' || parentDepartmentType == 'Function' || parentIsBusinessUnit) {
                        businessUnitFunction = parent.toString();
                    }
                    else {
                        businessUnitFunction = departmentSysId;    
                    }
                }
            } else {
                businessUnitFunction = departmentSysId;
            }

            //The 'dept_data' array pushes the required data and assignes these to the three variables from the 'consumer_orgs_list' variable set
            dept_data.push({
                consumer_organisation_id: departmentID,
                consumer_organisation: departmentSysId,
                business_unit_function: businessUnitFunction
            });
        }

        //Return the values in the 'dept_data' array
        return JSON.stringify(dept_data);
    },
 
I'm using the below OnLoad Catalogue Client script to get the results:
function onLoad() {

    var objData = _getBusinessApplicationIDFromURL(top.location.href);
    if (objData.success == true) {

        var strBusinessApplicationSysID = objData.sys_id;

        g_form.setValue('business_application', strBusinessApplicationSysID); // set the application service from the URL

        //retreive the list of assigned consumer organisations associated with the Business Application from the 'existingConsumerOrgs' function within the 'LBGConsumOrgsCatItem' Script Include
        var gaExistingConsumers = new GlideAjax('LBGConsumOrgsCatItem');
        gaExistingConsumers.addParam('sysparm_name', 'existingConsumerOrgs');
        gaExistingConsumers.addParam('sysparm_app', g_form.getValue('business_application'));
        gaExistingConsumers.getXML(parseScript);

        //Retreive the value of the 'Consumed Group Wide' field of the associated with the Business Application from the 'retrieveGroupWideField' function within the 'LBGConsumOrgsCatItem' Script Include
        var gaConsumedGroudWide = new GlideAjax('LBGConsumOrgsCatItem');
        gaConsumedGroudWide.addParam('sysparm_name', 'retrieveGroupWideField');
        gaConsumedGroudWide.addParam('sysparm_app', g_form.getValue('business_application'));
        gaConsumedGroudWide.getXML(parseGroupWideCheck);

    } else {

        g_form.addErrorMessage('Unfortunately this catalogue item has not loaded correctly and as a result will not work. Please try again');

    }

}

function parseScript(response) {
    //Populate the rows in the 'consumer_orgs_list' variable set with the list of existing consumer organisation entries
    var answer = response.responseXML.documentElement.getAttribute("answer");
    g_form.setValue("consumer_orgs_list", answer);

}

function parseGroupWideCheck(response) {
    //Get the result based from the "result" tag
    var result = response.responseXML.getElementsByTagName("result");

    //Clear out the below fields
    g_form.clearValue('business_unit_function');
    g_form.clearValue('consumer_organisation');
    g_form.clearValue('consumer_organisation_id');
    g_form.clearValue('selected_option');

    //If there are existing relationships, then set the list collector variable to be the array of consumers returned from gaConsumedGroudWide
    if (result != '') {
        //If the 'Consumed Group Wide' field on the Business Application is set true, update the below fields and show the below infoMessage
        if (result[0].getAttribute('gw_Check') == 'true') {
            g_form.setValue('selected_option', 'option_1');
            g_form.setReadOnly('selected_option', true);
            g_form.setValue('is_group_wide', true);
            g_form.addInfoMessage("This application is currently defined as being consumed group wide (i.e. supporting all business units, and group functions). If updated to support specific business areas then it will no longer be defined as 'Consumed Group Wide' and the existing relationships to all business units and group functions will be removed and replaced by the specific business areas selected below.");
            //Otherwise, update the below fields
        } else {
            g_form.setReadOnly('selected_option', false);
            g_form.clearValue('selected_option');
            g_form.setValue('is_group_wide', false);

        }
    }
}

function _getBusinessApplicationIDFromURL(urlAddress) {
    // extract the sys_id of the Application Service from the URL
    // it is the 32 characters after lbg_record=

    var objTemp = {};

    try {

        if (urlAddress.includes('lbg_record=')) {
            var passedURLData = urlAddress.split('lbg_record=')[1];

            var strBusinessApplication = passedURLData.substring(0, 32);
            // just check the length to ensure it is a full sys_id
            if (strBusinessApplication.length == 32) {
                objTemp.success = true;
                objTemp.sys_id = strBusinessApplication;
            } else {
                objTemp.success = false;
                objTemp.sys_id = 'ERROR';
            }
            return objTemp;

        } else {
            objTemp.success = false;
            objTemp.sys_id = 'ERROR';
            return objTemp;
        }

    } catch (myError) {
        objTemp.success = false;
        objTemp.sys_id = 'ERROR';
        return objTemp;
    }
}
 
However, I've been told that I need to merge the two GlideAjax calls into one. Does anyone know what I need to do to achieve that? 
4 REPLIES 4

Tanushree Maiti
Tera Patron

Hi @matthew_hughes 

 

What is your business requirement. Please explain.

 

 

Please Accept the solution if it assisted you with your question & Mark this response as Helpful.
Regards
Tanushree Maiti
ServiceNow Technical Architect
LinkedIn: https://www.linkedin.com/in/tanushreemaiti

matthew_hughes
Kilo Sage

Hi @Tanushree Maiti 

I'm wanting to combine both glideAjaxes gaExistingConsumers and gaConsumedGroudWide into one.

Hi @matthew_hughes 

 

Instead of firing two separate GlideAjax calls, pass all parameters at once to a single script include and parse the returned JSON.

 

 

Please Accept the solution if it assisted you with your question & Mark this response as Helpful.
Regards
Tanushree Maiti
ServiceNow Technical Architect
LinkedIn: https://www.linkedin.com/in/tanushreemaiti

Ankur Bawiskar
Tera Patron

@matthew_hughes 

try this

Script Include:

getBusinessAppData: function() {
    var busApp = this.getParameter('sysparm_app');

    var response = {
        gw_check: false,
        consumer_orgs: []
    };

    var grBusinessApp = new GlideRecord('cmdb_ci_business_app');
    if (grBusinessApp.get(busApp)) {
        response.gw_check = grBusinessApp.getValue('u_consumed_group_wide') == 'true';
    }

    var viewedDepartments = {};
    var grConsumerRecordEntries = new GlideRecord('u_m2m_depts_config_items');
    grConsumerRecordEntries.addQuery('u_configuration_item', busApp);
    grConsumerRecordEntries.addNotNullQuery('u_department');
    grConsumerRecordEntries.query();

    while (grConsumerRecordEntries.next()) {
        var departmentSysId = grConsumerRecordEntries.getValue('u_department');

        if (viewedDepartments[departmentSysId]) {
            continue;
        }
        viewedDepartments[departmentSysId] = true;

        var grDepartmentRecord = new GlideRecord('cmn_department');
        if (!grDepartmentRecord.get(departmentSysId)) {
            continue;
        }

        var departmentID = grDepartmentRecord.getValue('id');
        var parent = grDepartmentRecord.getValue('parent');
        var businessUnitFunction = departmentSysId;

        if (parent) {
            var grParentTypeCheck = new GlideRecord('cmn_department');
            if (grParentTypeCheck.get(parent)) {
                var parentDepartmentType = grParentTypeCheck.getValue('u_department_type');
                var parentIsBusinessUnit = grParentTypeCheck.getValue('u_business_unit') == 'true';

                if (parentDepartmentType == 'Business Unit' || parentDepartmentType == 'Function' || parentIsBusinessUnit) {
                    businessUnitFunction = parent.toString();
                }
            }
        }

        response.consumer_orgs.push({
            consumer_organisation_id: departmentID,
            consumer_organisation: departmentSysId,
            business_unit_function: businessUnitFunction
        });
    }

    return JSON.stringify(response);
},

Client Script

function onLoad() {
    var objData = _getBusinessApplicationIDFromURL(top.location.href);

    if (objData.success == true) {
        var strBusinessApplicationSysID = objData.sys_id;
        g_form.setValue('business_application', strBusinessApplicationSysID);

        var gaBusinessAppData = new GlideAjax('LBGConsumOrgsCatItem');
        gaBusinessAppData.addParam('sysparm_name', 'getBusinessAppData');
        gaBusinessAppData.addParam('sysparm_app', g_form.getValue('business_application'));
        gaBusinessAppData.getXML(handleBusinessAppData);
    } else {
        g_form.addErrorMessage('Unfortunately this catalogue item has not loaded correctly and as a result will not work. Please try again');
    }
}

function handleBusinessAppData(response) {
    var answer = response.responseXML.documentElement.getAttribute('answer');
    if (!answer) {
        return;
    }

    var data = JSON.parse(answer);

    g_form.setValue('consumer_orgs_list', JSON.stringify(data.consumer_orgs));

    g_form.clearValue('business_unit_function');
    g_form.clearValue('consumer_organisation');
    g_form.clearValue('consumer_organisation_id');
    g_form.clearValue('selected_option');

    if (data.gw_check) {
        g_form.setValue('selected_option', 'option_1');
        g_form.setReadOnly('selected_option', true);
        g_form.setValue('is_group_wide', true);
        g_form.addInfoMessage("This application is currently defined as being consumed group wide (i.e. supporting all business units, and group functions). If updated to support specific business areas then it will no longer be defined as 'Consumed Group Wide' and the existing relationships to all business units and group functions will be removed and replaced by the specific business areas selected below.");
    } else {
        g_form.setReadOnly('selected_option', false);
        g_form.clearValue('selected_option');
        g_form.setValue('is_group_wide', false);
    }
}

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  10x ServiceNow MVP  ||  ServiceNow Community Leader