Search code examples
javascriptjqueryhtmlssjssalesforce-marketing-cloud

Marketing cloud SSJS - javascript passing values between 2 scripts


I have a cloud pages.

On this page , i have

  1. SSJS script , which retrives records from a data extension. From the count column in the data extension , i want to create a array like

dataarray = [10,20,30,40,50]

  1. Then i need to pass this array (dataarray ) to another script where i can use it in d3.

The problem i am facing is how to pass values from a script which run at server to a script which run in client . I have tried hidden html element method which does not work and does not garrentte seq of script execution.

can you please advise how to pass values .

<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   <meta name="description" content="">
   <meta name="author" content="">
   <link rel="icon" href="https://www.abc.nl/favicon.ico">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
 </head>
 <body>
     <script runat="Server">
   		Platform.Load("core","1.1.5");
       var data_rec;
     	try
        {
          var myDE = DataExtension.Init('01_Reporting_Sent_Today');  
          var filter = {Property:'return',SimpleOperator:'equals',Value:'1'};
          var data = myDE.Rows.Retrieve(filter);   
          data_rec = data.length;    
          Write("<br/>The len is :" + Stringify(data_rec))
        }catch(ex)
        {
          	Write("<br/>The error is :" + Stringify(ex))
        }
   </script>
   <script>      

		  var datachart = [10,20,30,40,50];
     	  var canvas = d3.select("body")
            				.append("svg")
            				.attr("width",500)
            				.attr("height",500)
            var bars = canvas.selectAll("rect")
            				.data(datachart)
            				.enter()
            					.append("rect")
            					.attr("width",function (d) { return d;})
            					.attr("height",50);
     
          
   </script>
 </body>
</html>

so the dataarray from first script , i need to use in second script


Solution

  • You can use AMPScript to return the value inside the JS script:

    Update: fixed incorrect syntax in my example as pointed out by Reidenshi

    <script runat="server">
      ...
      var dataString = Stringify(data);
      Variable.SetValue("@dataString", dataString);
    </script>
    <script>
      var data = JSON.parse(%%=v(@dataString)=%%); 
    </script>