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.

Sharing Data Across Business Units: Overview and Best Practices

Key for understanding data elements of SFMC, including how large organizations operate through business units and how they store their data.

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(String(url).indexOf("?") > -1) {
		url = String(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> 

Convert Salesforce ID from 15 to 18 chars

Marketing Cloud only manages Salesforce IDs (such as Lead ID) that are 18 characters long.

%%=LongSFID('0036000000QKv5T')=%%
%%[
    SET @ID = "0036000000QKv5T"
    FOR @i = 0 TO 2 DO
        SET @f = 0
        FOR @j = 0 TO 4 DO
            SET @c = SUBSTRING(@ID, ADD(ADD(@j,1), MULTIPLY(@i, 5)), 1)
            SET @x = IIF(@j == 0, ADD(@j, 1), MULTIPLY(@x, 2))
            SET @f = IIF(NOT EMPTY(RegExMatch(@c, "[A-Z]", 0)), ADD(@f, @x), @f)
        NEXT @j
        SET @ID = CONCAT(@ID, SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ012345', ADD(@f, 1), 1));
    NEXT @i
    OUTPUTLINE(CONCAT(@ID))
]%%
<script runat="server">
    Platform.Load("core", "1");
	var id15 = "0036000000QKv5T";
    var id18 = longSFID(id15);
    Write(id18);
    function longSFID(id) {
        for (var i = 0; i < 3; i++) {
			var f = 0;
            for (var j = 0; j < 5; j++) {
                var c = id.charAt(i * 5 + j);
                if (c >= "A" && c <= "Z") {
                    f += 1 << j;
                }
            }
            id += "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345".charAt(f);
        }
        return id;
    }
</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>
<!-- OR -->
<p>© %%xtyear%% All rights reserved.</p> 

Have I missed anything?

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

  1. Re: Copyright info
    Something extremely simple but it should be included pretty much everywhere.

    © %%=Format(Now(),’yyyy’)=%% All rights reserved.

    Alternate method which seems easier?
    © %%xtyear%% All rights reserved.

  2. Thank you for the tip William, including it in the article right now 🙂

  3. Ivan, is there a solution in your opinion to pass data from client side to server side? I have a JS loop that uses basic client side functions and want to perform some SSJS functions in that loop. Not having much luck.

  4. I think this is only possible by sending an AJAX request.

Comments are closed.

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