Skip to content Skip to sidebar Skip to footer

Read Json Object In Csjs From Ssjs

I wanted to find out if its possible to send an array of json objects to csjs from ssjs in a sessionScope variable. When I try to use sesionScope.get in my script block. It doesn't

Solution 1:

In the xp:scriptBlock you are combining client side JS with server side JS. The server side JS code must be in #{javascript:<code>} in order to be parsed. So do this:

<xp:scriptBlock id="scriptBlock1">
    <xp:this.value><![CDATA[
        makeCharts = function() {
            //Create a new  2D Chartvar pieChart = new dojox.charting.Chart2D("#{id:panel1}");
            alert(sessionScope.get("chartData")); // Does not alert anything.// Add  the only/default  plot for  the pie chart
            pieChart.addPlot("default",  {type:  "Pie", radius: 150, fontColor:  "black", labels: false});
            // Add  the data series 
            pieChart.addSeries("Number  of Orders", #{javascript:sessionScope.get("chartData")});
            //Render the  chart!
            pieChart.render(); 
        };
        XSP.addOnLoad(makeCharts);
    ]]></xp:this.value>
</xp:scriptBlock>

Update: your SSJS Array() is not returned as you expect. If you use a simple String instead, you can see that the code works and sends data from SSJS to CSJS. Here's a simple example:

<xp:this.beforePageLoad><![CDATA[#{javascript:
    var resultArray = "[{y: 1978, text: \"Blue Widget\"},{y: 1669, text: \"Brown Widget\"},{y: 2017, text: \"Green Widget\"},{y: 334, text: \"Orange Widget\"},{y: 1051, text: \"Pink Widget\"},{y: 1545, text: \"Purple Widget\"},{y: 339, text: \"Red Widget\"},{y: 1067, text: \"Yellow Widget\"}]";
    
    sessionScope.chartData = resultArray;
}]]></xp:this.beforePageLoad><xp:scriptBlockid="scriptBlock1"><xp:this.value><![CDATA[
        makeCharts = function() {
            console.log(#{javascript:sessionScope.get("chartData")});
        };
        XSP.addOnLoad(makeCharts);
    ]]></xp:this.value></xp:scriptBlock>

Solution 2:

You can bind scoped variable into hidden text field. Ensure it has readOnly attribute set to false. See https://stackoverflow.com/a/15948134/206265

In your CSJS then get its value just by:

var field = document.getElementById("#{id:hiddenInput1}");
myJson = field.value;

Post a Comment for "Read Json Object In Csjs From Ssjs"