1

I was wondering if I can save data from an SSJS function in the client to use in JS scripts that run on the client-side after page load. For example, get value from ampscript, then set that value as a variable in an SSJS script like below, then access that variable on the client.

%%[
set @name = Lookup ('Leads', 'name', 'id', _subscriberKey)
]%%
 <script runat=server language="JavaScript">
   Platform.Load("core", "1.1.1");
   var name = Variable.GetValue("@name");
   Variable.SetValue("@name_ssjs", name);
 </script>

Is there a way I can access that variable with a normal client-side script? I have seen the use of AJAX so that SSJS can access a client-side variable. But I have not seen anything that explains how the client can access SSJS variables.

1 Answer 1

4

Yes, this is most certainly possible! To accomplish this, you would output your Server-side variables the same as you would in HTML - via inline declarations or using Output() (AMPScript) or Write() (SSJS).

When using SSJS you canuse the inline declaration of <ctrl:var name="myVar" />(see my blog post here for some more detailed information on the capabilities of this) to push this variable into your existing Client-side JS.

Example:

<script runat=server>
var myVar = "Hello";
</script>
<script>
console.log('<ctrl:var name="myVar" />');
</script>

The other option in SSJS is to write your Client-side JS code through a Write(). This would have it 'hard coded' into the response given to the requesting browser.

Example:

<script runat=server>
var myVar = "Hello";
Platform.Response.Write("<script>console.log(" + myVar + ");</script>")
</script>

For AMPScript, you could use an inline declaration of %%=v(@myVar)=%% to push your Server-side variable into Client-side JS. This would add it into an existing script written outside your Server-side code.

%%[
SET @myVar = "Hello"
]%%
<script>
console.log('%%=v(@myVar)=%%');
</script>

But, if you would rather handle the building of your code at the server level via AMPScript, you can use Output() combined with a CONCAT() to create the script same as a Write() in SSJS.

Example:

%%[
SET @myVar = "Hello"
OUTPUT(CONCAT("<script>console.log(",@myVar,");</script>"))
]%%

IMPORTANT NOTE: Be aware this will move that info to the 'front-end' which can be read by anyone that is looking at the source code, so no private or secure info should be passed from Server-Side to Client-side.

2
  • 1
    Disregard my previous comment. Your sentence structure is a bit weird, I think, but still correct.
    – sfdcfox
    Commented Jul 14, 2020 at 21:29
  • Yeah i might edit it tomorrow to be a bit more coherent. I was typing it on my phone waiting to pick up deli meat so I was a bit distracted Commented Jul 15, 2020 at 0:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .