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">

  var CodeP = Variable.GetValue("@CodeP");
  Write("<br>CodeP: " + CodeP);


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?

  • You don't have to write "type" part, why don't you use it with just <script runat="server">? – Selim Sevim Aug 20 '18 at 7:55
  • can you provide more context? This sounds like an outlying syntax issue and not an issue with the GetValue function. – Gortonington Aug 20 '18 at 12:45

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:

  // Retrieve value of hidden field
  var codeP = document.getElementById("CodeP").value;
  // Retrieve inner html of the p tag
  var codeP = document.getElementById("CodeP").innerHTML;
| improve this answer | |
  • This is exactly what I did as a workaround. Thank you for sharing the info @ncv – kuml Aug 27 '18 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.