[SalesForce] can i pass variable values from ampscript to javascript

i have a cloud page in marketing cloud.

In cloud page, I am using ampscript and javascript both. Can i pass variables values from my ampscript to javascript directly?

I have already tried this example:

%%[

var @CodeP
set @CodeP = RequestParameter("j")

]%%

<script runat="server">

  Platform.Load("Core","1");
  var CodeP = Variable.GetValue("@CodeP");
  Write("<br>CodeP: " + CodeP);

</script>

The problem is that this approach breaks my javascript because my javascript on cloud page starts with this:

 <script type="text/javascript">

Adding runat="server" breaks the existing functionality of my javascript.

please help?

Best Answer

I think what you are missing here is that Salesforce Marketing Cloud Server Side JavaScript is not the same as JavaScript that runs on the browser. Adding runat="server" to the script block causes your code to be executed by the SFMC server as Server Side JavaScript, meaning if it includes any of the standard browser JavaScript functions like DOM manipulation, it will not work. In fact, it will not even load on the page and will possibly throw a server error due to the limitations of what SFMC will allow you to run server side.

The Variable.GetValue function is specific to Server Side JavaScript and will not work to pass the value of the variable to browser JavaScript. To do so, the best way I have found is to create a hidden form field or div with the value of the variable like this:

<input id="CodeP" type="hidden" value="%%=v(@CodeP)=%%">

Or this:

<div style="display:none;"><p id="CodeP">%%=v(@CodeP)=%%</p></div>

You can then retrieve that value in you JavaScript like this:

<script>
  // Retrieve value of hidden field
  var codeP = document.getElementById("CodeP").value;
  // Retrieve inner html of the p tag
  var codeP = document.getElementById("CodeP").innerHTML;
</script>
Related Topic