'custom widget in service portal: server script variable not readable from client script

I am populating an object with country information in the server script of my custom widget and trying to read it from the client script.

Server Script:

data.vendorCountry = {};

if (input.existingvendor) {
        getVendor(input.existingvendor);
    }


    function getVendor(vnd) {
        var gr = new GlideRecord('u_vendors');
        gr.addQuery('sys_id', vnd);
        gr.query();
        if (gr.next()) {
            data.newVendor.name = gr.getValue('u_name');
            data.newVendor.street = gr.getValue('u_street');
            data.newVendor.city = gr.getValue('u_city');
            data.newVendor.zip = gr.getValue('u_zip');
            data.newVendor.billingid = gr.getValue('u_billing_id');
            data.newVendor.invoiceid = gr.getValue('u_invoiceid');
            data.newVendor.country = gr.getDisplayValue('u_country');
                    
                    // get the country name and sys_id for the existing vendor
                    var grVendorCountry = new GlideRecord('core_country');
                    grVendorCountry.addQuery('name', data.newVendor.country);
                    grVendorCountry.query();
                    if(grVendorCountry.next()) {
                        data.vendorCountry = grVendorCountry;
console.log(data.vendorCountry);
                    }
        }
    }

Client Script:

$scope.vendorselection= function(val) {
    c.data.action = 'submit';
    c.data.existingvendor = val;
    c.server.update().then(function() {
                if(c.data.vendorCountry){
                    $scope.country = {
                        displayValue: c.data.vendorCountry.name,
                        value: c.data.vendorCountry.sys_id,
                        name: 'location'
                    };
                                console.log(c.data.vendorCountry);
                    }
                
            });
    
}

Result of console.log(data.vendorCountry); is a proper object with country information such as name, sys_id

Result of console.log(c.data.vendorCountry); is [object Object]



Solution 1:[1]

The reason why this happens is because if you do a console.log inside the server script toString will be called on vendorCountry. The Server Script can't directly log to the javascript console in the browser, you could do console.log(JSON.stringify(c.data.vendorCountry)) but I would advise you to use $sp.log(c.data.vendorCountry) inside the server script for logging.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 makim