Best tips and tricks in AMPscript and server-side Javascript

Best tips and tricks in AMPscript and server-side Javascript

This article showcases the best and most useful bits of AMPscript and server-side Javascript in Salesforce Marketing Cloud.

Retrieve the data

The most common practice for retrieving the data from a form submission or an HTTP request. Easier in AMPscript than SSJS, but it works in the same way.

%%[
	SET @Name = RequestParameter("name")
	SET @Email = QueryParameter("email")
	SET @CurrentURL = RequestParameter('PAGEURL')
	SET @Referer = HTTPRequestHeader("Referer")
]%%
<script runat="server">
    Platform.Load("core", "1.1.1");
    var name = Request.GetFormField("name");
	var email = Request.GetQueryStringParameter("email");
	var currentUrl = Platform.Request.RequestURL;
	var referer = Platform.Request.ReferrerURL;
</script>

Remove parameters from an URL

An alternative to using regular expressions. This time, it’s SSJS which is easier to implement.

%%[
	SET @URL = "https://example.com?name=Jon"
	IF IndexOf(@URL,'?') > 0 THEN
		SET @URL = Substring(@URL,0,Subtract(IndexOf(@URL,'?'),1))
	ENDIF
]%%	
<script runat="server">
    Platform.Load("core","1.1");
	var url = "https://example.com?name=Jon";
	if(url.indexOf("?") > 0) {
		url = url.split('?')[0];
	}
</script>

Pass the value from one language to another

Passing the value from AMPscript to server-side Javascript to client-side Javascript.

%%[
	SET @Data = "Guns"
]%%
<script runat="server">
    Platform.Load("core","1.1");
    var data = Platform.Variable.GetValue("@Data");
	var newData = Platform.Variable.SetValue("@Data", data + " & Roses");
</script>
<script runat="client">
	console.log(`%%=v(@Data)=%%`);
</script> 

Create a timestamp

Useful in some cases of date comparison or for creating a unique Id without using the GUID() function. As usual, AMPscript rules when it comes to managing dates.

%%[
	SET @Random = RANDOM(100, 999)
	SET @Format = Format(Now(), "yyyyMMddhhmmss")
	SET @TimeStamp = CONCAT(@Format, @Random)
]%%
<script runat="server">
    Platform.Load("core","1.1");
	var now = new Date();
    var timeStamp = now.getFullYear() 
        + addZero(now.getMonth()+1) 
        + addZero(now.getDate()) 
        + addZero(now.getHours()) 
        + addZero(now.getMinutes()) 
        + addZero(now.getSeconds())
		+ random(100,999);

    function addZero(n) {
	    return n < 10 ? '0' + n : n
    }
	
	function random(min, max) {
		min = Math.ceil(min);
		max = Math.floor(max);
		return Math.floor(Math.random() * (max - min)) + min;
    }
</script>	

Convert the date

Converting the date from system to local makes your database more consistent.

%%[
	SET @LocalTime = SystemDateToLocalDate(NOW())
	SET @SystemTime = LocalDateToSystemDate(NOW())
]%%
<script runat="server">
    Platform.Load("core","1.1");
	var localTime = DateTime.SystemDateToLocalDate(Now());
	var systemTime = DateTime.LocalDateToSystemDate(Now());
</script> 

Retrieve the info about an object

Have you ever wondered how the Marketing Cloud objects are built? Here is you answer.

<script runat="server">
    Platform.Load("core","1.1");
    var prox = new Script.Util.WSProxy();
    var res = prox.describe("DataExtension");
    Write(Stringify(res));
</script>

Each object has a CustomerKey. We can retrieve all the info about a particular object using this method. In this case, a DataExtension.

<script runat="server">
    Platform.Load("core","1.1");
	var filter = {
		Property:"CustomerKey",
		SimpleOperator:"equals",
		Value:"TYPE-YOUR-CUSTOMER-KEY-HERE"
	}
  	var results = DataExtension.Retrieve(filter);
    Write(Stringify(results));
</script>

Print a variable

Copy-paste this bit whenever you need to print a value of a variable fast.

%%[
	SET @Str = "Hello World!"
	OUTPUTLINE(CONCAT("<br><pre>",@Str,"</pre><br>"))
]%%
<script runat="server">
    Platform.Load("core","1.1");
	var str = "Hello World!";
    function dump(variable, label) {
		var label = (label == undefined) ? '' : '<b>' + label + ':</b><br>';
		Write("<br><pre>" + label + Stringify(variable) + "</pre><br>");
	}
    dump(str,"String: ");
</script>

Get a JSON from a Marketing Cloud page

Just a reminder, we need Accept-Encoding header to be able to receive an uncompressed response from a Marketing Cloud resource or page.

<script runat="server">
    Platform.Load("core","1.1");
	var req = HTTP.Get('https://mc-website/mc.json', ['Accept-Encoding'], ['identity']);
	var obj = Platform.Function.ParseJSON(String(req.Content));
</script>

Set a cookie (+1d)

Fortunately for us, server-side Javascript is able to set or get a cookie from the browser.

<script runat="server">
	Platform.Load("core", "1.1");
	var endDate = new Date();
	endDate.setDate(endDate.getDate() + 1);
	var val = "Eggs";
	Platform.Response.SetCookie("Basket", val, endDate, true);
</script>

Debug AMPscript with SSJS

To some extent, there is a way to debug a faulty AMPscript expression. A very messy way.

<script runat="server">
	Platform.Load("core","1");
	try {
</script>
%%[
	LookupRows('UnexistingDataExtension','Id',0)
]%%
<script runat="server">
	}
	catch (err) {
		Variable.SetValue("errorMessage", Stringify(err.message) + Stringify(err.description));
	}
</script> 
<script runat="client">
	console.log(`%%=v(@errorMessage)=%%`);
</script> 

Create a greeting

A useful bit of AMPscript that should decorate the intro of every email.

<h1>
	%%[ IF @Gender == "M" THEN ]%%
		Kind Sir
	%%[ ELSEIF @Gender == "W" THEN ]%%
		My good Lady	
	%%[ ELSE ]%%
		Dear friend
	%%[ ENDIF ]%%
	&sp;welcome to the Hunger Games!
</h1>	

Print email name and id

When something’s wrong with an email, it’s extremely useful to include a hidden info about it somewhere in the body, so the email can be easily found through the Content Builder.

<p>Email name: <strong>%%emailName_%%</strong></p>
<p>Email Id: <strong>%%_emailid%%</strong></p>

Include an HTML block from Content Builder

Did you know we can store some HTML bits in Content Builder and then include them on a Cloud page? Now you know.

%%=ContentBlockbyId("123456")=%%

Copyright info

Something extremely simple but it should be included pretty much everywhere.

<p>© %%=Format(Now(),'yyyy')=%% All rights reserved.</p>

Have I missed anything?

Please poke me with a sharp comment below or use the contact form.

Pay me a coffee

Want to say thanks? Pay me a coffee! Remember, I turn coffee into code.

Leave a Reply

Your email address will not be published. Required fields are marked *

ampscript
Up Next:

How to create a listless double opt-in in Marketing Cloud with AMPscript

How to create a listless double opt-in in Marketing Cloud with AMPscript