Code snippets

Wish to skip the tedious reading and jump to the code? Here are some working code snippets you can use!

How to generate a Data Extension with random records using server-side JavaScript

Not enough info? Jump to the article.

<script runat="server">

	Platform.Load("core", "1.1");

	var insrt = createDemoDataExtension("MyDataExtension","MyFolder",3000);

	function createDemoDataExtension(name, folder, num) {

		var api = new Script.Util.WSProxy();

		var fields = [
			{
				"Name": "Primary",
				"FieldType": "Text",
				"IsPrimaryKey": true,
				"IsRequired": true,
				"MaxLength": 50
			},
			{
				"Name": "Text_with_Default",
				"FieldType": "Text",
				"MaxLength": 50,
				"DefaultValue": "Hellow world"
			},
			{
				"Name": "Number",
				"FieldType": "Number"
			},
			{
				"Name": "Date",
				"FieldType": "Date"
			},
			{
				"Name": "Boolean",
				"FieldType": "Boolean",
				"DefaultValue": false
			},
			{
				"Name": "Email",
				"FieldType": "EmailAddress"
			},
			{
				"Name": "Phone",
				"FieldType": "Phone"
			},
			{
				"Name": "Decimal",
				"FieldType": "Decimal",
				"MaxLength": 18,
				"Scale": 2
			},
			{
				"Name": "Locale",
				"FieldType": "Locale"
			},
			{
				"Name": "Text_required",
				"FieldType": "Text",
				"MaxLength": 50,
				"IsRequired": true
			}
		];

		var conf = {
			"CustomerKey": Platform.Function.GUID(),
			"Name": name,
			"Fields": fields
		};

		var req = Folder.Retrieve({ Property: 'Name', SimpleOperator: 'equals', Value: folder });

		var catId = req[0].ID;

		if (catId != null) conf["CategoryID"] = catId;

		var res = api.createItem("DataExtension", conf);

		if (res["Status"] == "OK") {

			var message = '(+) Data Extension "' + name + '" has been created';

			if (catId != null) message += ' in the folder "' + folder + '".'; else message += ' in the root folder.';

			Write(message + "<br>");

			var customerKey = res.Results[0].Object.CustomerKey;

			var de = DataExtension.Init(customerKey);

			var payload = [];

			for (var i = 0; i < num; i++) {
				var obj = {};
				for (k in fields) {
					obj[fields[k].Name] = (fields[k].FieldType == "Text" && fields[k].IsPrimaryKey == true) ? Platform.Function.GUID() : getRandom(fields[k].FieldType);
				}
				payload.push(obj);
			}

			var addedRowCount = de.Rows.Add(payload);

			Write("(+) Rows added: " + Stringify(addedRowCount) + "<br>"); 

			return addedRowCount;

		} else {
			Write("(-) Something went wrong: " + Stringify(res.Results[0].StatusMessage));
		}

		function getRandom(type) {

			if(type == "Decimal") return Math.floor(Math.random() * (1000 - 100) + 100) / 100;
			if(type == "EmailAddress") return Math.floor(Math.random() * 10000000000) + "@mail.com";
			if(type == "Boolean") return (Math.random() >= 0.5);
			if(type == "Number") return Math.floor(Math.random() * 100);
			if(type == "Date") return new Date(+(new Date()) - Math.floor(Math.random() * 10000000000));

			if(type == "Phone") {
				var n = "0";
				for (var i = 0; i < 9; i++) {
					n += Math.floor(Math.random() * 9)
				}
				return n;
			}

			if(type == "Locale") {
				switch (Math.floor(Math.random() * 4)) {
					case 0: var loc = "FR"; break;
					case 1: var loc = "NL"; break;
					case 2: var loc = "DE"; break;
					case 3: var loc = "EN"; break;
				}
				return loc;
			}

			if(type ==  "Text") {
				var str = "lorem ipsum dolor sit amet consectetur adipiscing elit donec vel nunc eget augue dignissim bibendum";
				arr = str.split(" ");
				var ctr = arr.length, temp, index;
				while (ctr > 0) {
					index = Math.floor(Math.random() * ctr);
					ctr--;
					temp = arr[ctr];
					arr[ctr] = arr[index];
					arr[index] = temp;
				}
				str = arr.join(" ");
				return str;
			}
		}
	}
</script>

How to trigger a Journey API Entry event with AMPscript and SSJS

Not enough info? Jump to the article.

%%[

    SET @SubscriberKey = "0x00000001"
    SET @EmailAddress = "icedtea@bag.com"
    SET @PostalCode = "2000"

]%%
<script runat="server">

    Platform.Load("Core", "1.1.1");

    var data = {
        SubscriberKey: Variable.GetValue("@SubscriberKey"),
        EmailAddress: Variable.GetValue("@EmailAddress"),
        PostalCode: Variable.GetValue("@PostalCode")
    }

    var setup = {
		authBaseURI: "https://xxxxxxxxxxxxxxxxxxxx-xxxxxxx.auth.marketingcloudapis.com/",
		restBaseURI: "https://xxxxxxxxxxxxxxxxxxxx-xxxxxxx.rest.marketingcloudapis.com/",
		clientId: "xxxxxxxxxxxxxxxxxxxxxxxx",
		clientSecret: "xxxxxxxxxxxxxxxxxxxxxxxx",
		eventDefinitionKey: "APIEvent-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
	}

    try {
        var token = getToken(setup);
        var success = false;
        if (!!token) success = triggerEvent(token, setup, data); 
        if (!!success) Write("Subscriber was successfully injected into the Journey"); 
        else  Write("Failed to inject subscriber into the Journey");
    } catch (err) {
        Write("Error: " + Stringify(err));
    }

    function getToken(setup) {

        var config = {
            url : setup.authBaseURI + "v2/token",
            contentType : "application/json",
            payload : {
                "client_id": setup.clientId,
                "client_secret": setup.clientSecret,
                "grant_type": "client_credentials"
            }
        }

        var req = HTTP.Post(config.url, config.contentType, Stringify(config.payload));

        if (req.StatusCode == 200) {
            var res = Platform.Function.ParseJSON(req.Response[0]);
            return res.access_token;
        } else {
            return false;
        }

    }

    function triggerEvent(token, setup, data) {

        var config = {
            url : setup.restBaseURI + "interaction/v1/events",
            contentType : "application/json",
            headerName : ["Authorization"],
            headerValue : ["Bearer " + token],
            payload : {
                ContactKey: data.SubscriberKey,
                EventDefinitionKey: setup.eventDefinitionKey,
                Data: data
            }
        }

        var req = HTTP.Post(config.url, config.contentType, Stringify(config.payload), config.headerName, config.headerValue);

        if (req.StatusCode == 201) {
            var res = Platform.Function.ParseJSON(req["Response"][0]);
            if (res.eventInstanceId != null && res.eventInstanceId != "") return true;
        } else {
            return false;
        }
        
    }

</script>

How to enhance your forms with AJAX using AMPscript and plain Javascript

Not enough info? Jump to the article.

JSON page

%%[
	SET @AlreadyInUse = false
	SET @EmailAddress = RequestParameter('email')
	IF NOT EMPTY(@EmailAddress) THEN
		SET @Id = Lookup('Subscriptions','Id','EmailAddress',@EmailAddress)
		IF NOT EMPTY(@Id) THEN
			SET @AlreadyInUse = true
		ENDIF
	ENDIF
]%%
{
	"AlreadyInUse" : %%=v(Lowercase(@AlreadyInUse))=%%
}

Cloud page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud page</title>
</head>
<body>
	<form action="" method="post">
		<input id="email" name="EmailAddress" type="email" placeholder="Your email" required>
		<button>Does it exist?</button>
	</form>
	<script>
		var form = document.querySelector('form');
		var button = document.querySelector('button');
		var email = document.querySelector('input');
		form.addEventListener("submit", onFormSubmit, false);
		function onFormSubmit(e) {
			e.preventDefault();
			button.disabled = true;
			var xhr = new XMLHttpRequest();
			xhr.onload = function () {
				if (xhr.status >= 200 && xhr.status < 300) {
					var response = JSON.parse(xhr.response);
					if(response['AlreadyInUse'] == true) {
						button.disabled = false;
						alert('This email is already in use');
					} else {
						form.submit(); 
					}
				} else {
					alert('The request failed!');
				}
			};
			xhr.open('POST', 'https://somedomain.com/subscriptions?email=' + email.value);    
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xhr.send();
		}
	</script>
</body>
</html>	

How to loop through multiple delimited strings with AMPscript

Not enough info? Jump to the article.

<table>
%%[
SET @String = "John|Malkovitch|john.malkovitch@mail.com|USA|Jacques|Cousteau|jacques.cousteau@free.fr|France"
SET @Inc = 0
SET @MaxLength = 4

SET @StringRows = BuildRowsetFromString(@String,'|')

FOR @i = 1 to ROWCOUNT(@StringRows) DO

    SET @StringSet = CONCAT(@StringSet,Field(ROW(@StringRows, @i),1),"|")
    SET @Inc = ADD(@Inc,1)

    IF @Inc == @MaxLength THEN 

        SET @StringSetRows = BuildRowsetFromString(@StringSet,'|')

        ]%%<tr>%%[

            FOR @j = 1 to SUBTRACT(ROWCOUNT(@StringSetRows),1) DO

                SET @Record = Field(ROW(@StringSetRows, @j),1))

                ]%%<td>%%=v(@Record)=%%</td>%%[

            NEXT @j

        ]%%</tr>%%[

        SET @StringSet = ""
        SET @Inc = 0

    ENDIF
  
NEXT @i
]%%
</table>

How to create a link with an expiration date using AMPscript

Not enough info? Jump to the article.

Email message

%%[
	SET @RedirectPageID = 1234
	SET @SendDate = SystemDateToLocalDate(NOW())
	SET @ExpiredIn = 1
	SET @Destination = 'http://example.com'
	SET @Fallback = 'http://google.com'
]%%
<a href="%%=RedirectTo(CloudPagesURL(@RedirectPageID,'SendDate',@SendDate,'ExpiredIn',@ExpiredIn,'Destination',@Destination,'Fallback',@Fallback)=%%">
	Click me
</a>

Redirect page

%%[
    SET @SendDate = QueryParameter("SendDate")
	SET @ExpiredIn = QueryParameter("ExpiredIn")
	SET @Destination = QueryParameter("Destination")
	SET @Fallback = QueryParameter("Fallback")
    SET @Today = SystemDateToLocalDate(NOW())

	IF NOT EMPTY(@SendDate) AND NOT EMPTY(@ExpiredIn) THEN
		IF (DateDiff(@SendDate,@Today,'D') >= @ExpiredIn) THEN
			Redirect(@Destination)
		ELSE
			Redirect(@Fallback)
		ENDIF 
	ENDIF 
]%%

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

Not enough info? Jump to the article.

Email

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Confirmation Email</title>
</head>
<body>
    <a href="%%=RedirectTo(CloudPagesURL(7788,'token',AttributeValue('Token')))=%%">Confirm your subscription</a>
    <custom name="opencounter" type="tracking" />
</body>
</html>

Form

%%[

SET @formHandlerPageId = 7788
SET @action = RequestParameter("action")
SET @pageUrl = RequestParameter('PAGEURL')

IF IndexOf(@pageUrl,'?') > 0 THEN
    SET @pageUrl = Substring(@pageUrl,0,Subtract(IndexOf(@pageUrl,'?'),1))
ENDIF

]%%
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Subscription Form</title>
    <style>
        .wrapper {
            width:600px;
            min-height: 300px;
            margin: 5% auto 0;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <h1>Newsletter subscription.</h1>
        %%[ IF @action == "confirm" THEN ]%%
            <p>Please check your email.</p>
        %%[ ELSEIF @action == "success" THEN ]%%
            <p>Thank you for subscribing.</p>
            <p><a href="%%=v(@pageUrl)=%%">Go back</a></p>
        %%[ ELSEIF @action == "error" THEN ]%%
            <p>Your token is missing or has expired.</p>
            <p><a href="%%=v(@pageUrl)=%%">Please try again</a></p>
        %%[ ELSEIF @action == "exist" THEN ]%%
            <p>Your are already subscribed.</p>
            <p><a href="%%=v(@pageUrl)=%%">Go back</a></p>
        %%[ ELSE ]%%
            <form method="POST" action="%%=CloudPagesURL(@formHandlerPageId)=%%">
                <label for="Email">Your email:</label><br>
                <input name="email" type="email" placeholder="ex: jon.snow@winterfell.co.uk">
                <br>
                <button>Subscribe me</button>
            </form>
        %%[ ENDIF ]%%
    </div>
</body>
</html>

Form handler

%%[
    SET @email = RequestParameter("email")
    SET @token = RequestParameter("token")
    SET @today = SystemDateToLocalDate(NOW())

    SET @ts_externalKey = 112233
    SET @formPageId = 4455

    IF NOT EMPTY(@email) THEN

        IF Lookup("Consents","Opt-In","Email",@email) == "True" THEN
            Redirect(CloudPagesURL(@formPageId,"action","exist"))
        ENDIF

        SET @token = GUID()

        UpsertDE("Consents",1,"Email",@email,"Opt-In","False")
        UpsertDE("Tokens",1,"Email",@email,"Token",@token,"CreatedDate",@today)

        IF NOT EMPTY(@ts_externalKey) THEN

            SET @ts = CreateObject("TriggeredSend")
            SET @ts_definition = CreateObject("TriggeredSendDefinition")
            SetObjectProperty(@ts_definition, "CustomerKey", @ts_externalKey)
            SetObjectProperty(@ts, "TriggeredSendDefinition", @ts_definition)

            SET @ts_subscriber = CreateObject("Subscriber")
            SetObjectProperty(@ts_subscriber, "EmailAddress", @email) 
            SetObjectProperty(@ts_subscriber, "SubscriberKey", @email) 

            SET @ts_token = CreateObject("Attribute")
            SetObjectProperty(@ts_token, "Name", "Token")
            SetObjectProperty(@ts_token,"Value", @token)
            AddObjectArrayItem(@ts, "Attributes", @ts_token)

            AddObjectArrayItem(@ts, "Subscribers", @ts_subscriber)  
            
            InvokeCreate(@ts, @statusMsg, @errorCode) 

        ENDIF

        Redirect(CloudPagesURL(@formPageId,"action","confirm"))

    ELSEIF NOT EMPTY(@token) THEN

        SET @createdDate = Lookup("Tokens","CreatedDate","Token",@token)
        SET @email = Lookup("Tokens","Email","Token",@token)

        IF NOT EMPTY(@createdDate) AND @today < DateAdd(@createdDate, 15, "MI")  THEN

            UpdateData("Consents",1,"Email",@email,"Opt-In","True")
            
            Redirect(CloudPagesURL(@formPageId,"action","success")) 

        ELSE

            Redirect(CloudPagesURL(@formPageId,"action","error")) 

        ENDIF

    ELSE
        Redirect(CloudPagesURL(@formPageId,"action","error")) 
    ENDIF
]%%

How to clone a Data Extension and its records with server-side Javascript

Not enough info? Jump to the article.

<script runat="server">
    Platform.Load("core", "1.1");

    var resp = cloneDataExtension('MyDataExtension','MyFolder','SubscriberKey');
    Write(resp);

    function cloneDataExtension(extName,folderName,fieldKey) {

        var prox = new Script.Util.WSProxy();

        var req1 = Folder.Retrieve({Property:'Name',SimpleOperator:'equals',Value:folderName});
        var FolderID = req1[0].ID;

        var req2 = DataExtension.Retrieve({Property:"Name",SimpleOperator:"equals",Value:extName});
        var CustomerKey = req2[0].CustomerKey;

        var DE = DataExtension.Init(CustomerKey);
        var fields = DE.Fields.Retrieve();
        
        var filter = {
            LeftOperand: { Property:fieldKey,SimpleOperator:"isNotNull" },
            LogicalOperator: "OR",
            RightOperand: { Property:fieldKey,SimpleOperator:"isNull" }
        }

        var records = DE.Rows.Retrieve(filter);

        for(var i = 0; i < fields.length; i++) {
            if(fields[i]['IsPrimaryKey'] == true ) fields[i]['IsRequired'] = true;
        }

        var NewCustomerKey = Platform.Function.GUID();

        var ClonedDE = {
            'CustomerKey' : NewCustomerKey,
            'Name' : extName + ' clone',
            'CategoryID': FolderID,
            'Fields' : fields
        }

        var res = prox.createItem("DataExtension", ClonedDE);
        var message = res.Results[0].StatusCode + ": " + res.Results[0].StatusMessage;

        try {
            var DE2 = DataExtension.Init(NewCustomerKey);
            var res2 = DE2.Rows.Add(records);
            message += "Records added: " + res2;
        } catch(err) {
            message += "No records added";
        }

        return message;

    }
</script>

How to send an HTTP request from one Marketing Cloud page to another

Not enough info? Jump to the article.

AMPscript

/* FIRST PAGE */
%%[
	SET @payload = 'name=Doctor'
 	SET @req = HTTPPost2(CloudPagesURL(2181),'application/x-www-form-urlencoded', @payload, true, @resp, @respheader, 'Accept-Encoding', 'identity')
    IF @req == 200 THEN
  		OUTPUTLINE(CONCAT(@resp))
    ELSE
     	OUTPUTLINE(CONCAT('HTTP request was unsuccessful'))
    ENDIF
]%%
	
/* TARGET PAGE */
%%[
	SET @Name = RequestParameter("name")
	IF @Name == "Doctor" THEN
		OUTPUT(CONCAT("Who?"))
	ENDIF
]%%	

Server-side Javascript

<!-- FIRST PAGE -->
<script runat="server">
    Platform.Load("Core", "1.1.1")
	var payload = 'name=Doctor';
    var req = HTTP.Post('https://yourmcdomain.com/target-page', 'application/x-www-form-urlencoded', payload, ['Accept-Encoding'], ['identity']);
  	if(req.StatusCode == 200) {
       Write(String(req.Response));
    } else {
       Write('HTTP request was unsuccessful');
    }
</script>

<!-- TARGET PAGE -->
<script runat="server">
    Platform.Load("Core", "1.1.1")
    var name = Request.GetFormField("name");
    if(name == 'Doctor') {
       Write('Who?');
    }
</script>

How to retrieve records using complex filters with server-side Javascript

Not enough info? Jump to the article.

<script runat="server">
    Platform.Load("core","1.1.1");
	var DE = DataExtension.Init("0000-1111-2222-4444-6666");
	var complexFilter = {
		LeftOperand: {
			Property: "Adult", 
			SimpleOperator: "equals", 
			Value: true 
		},
        LogicalOperator: "OR",
        RightOperand: {
			LeftOperand: {
				Property: "Age", 
				SimpleOperator: "isNotNull"
			},
			LogicalOperator: "AND",
			RightOperand: {
				Property: "Age", 
				SimpleOperator: "greaterThan", 
				Value: 18 
			}
		}
	}
	var adults = DE.Rows.Retrieve(complexFilter);
</script>

How to create an expiration date for Cloud pages

Not enough info? Jump to the article.

AMPscript

<!doctype html>
<html>
<body>
	%%[
    	SET @Now = SystemDateToLocalDate(NOW())
		SET @EndDateRows = LookupRows("DatesDE","Page name","My awesome page")
		IF ROWCOUNT(@EndDateRows) > 0 THEN
        	FOR @i = 1 TO ROWCOUNT(@EndDateRows) DO
              SET @EndDate = FIELD(ROW(@EndDateRows,@i),'End date')
              SET @RedirectURL = FIELD(ROW(@EndDateRows,@i),'Redirect')
              IF DateDiff(@Now,@EndDate,"D") > 0 THEN
                  Redirect(@RedirectURL)
              ENDIF
            NEXT @i
		ENDIF
	]%%
	<h1>Expiration date w/ AMPscript</h1>
</body>
</html>

Server-side Javascript

<!doctype html>
<html>
<body>
	<script runat="server">
        Platform.Load("core","1.1");
      	var Now = DateTime.SystemDateToLocalDate(Now());
		var DatesDE = DataExtension.Init('DatesDE');
        var EndDateRows = DatesDE.Rows.Lookup(['Page name'],['My awesome page']);
      	if(EndDateRows.length > 0) {
          	for(i = 0; i < EndDateRows.length; i++)  {
        		var EndDate = new Date(EndDateRows[i]['End date']);
        		var RedirectURL = EndDateRows[i]['Redirect'];
                if (Now < EndDate) {
                  	Redirect(RedirectURL,false);
                } 
            }    
        }
	</script>	
	<h1>Expiration date w/ SSJS</h1>
</body>
</html>

How to send a Triggered Send email with server-side Javascript

Not enough info? Jump to the article.

%%[
	SET @TriggeredSendExternalKey = "123456"
	SET @SubscriberKey = Format(SystemDateToLocalDate(NOW()), "yyddMMhhmmss")
    SET @FirstName = "Borat"
    SET @EmailAddress = "youremailaddress@mail.com"
	SET @Language = "EN"
]%%
<script runat="server">

    Platform.Load("core","1.1");
  
    var data = {
       	attributes : {
      		FirstName: Platform.Variable.GetValue("@FirstName"),
			Language: Platform.Variable.GetValue("@Language")
    	},
      	subscriber : {
    		EmailAddress: Platform.Variable.GetValue("@EmailAddress"),
      		SubscriberKey: Platform.Variable.GetValue("@SubscriberKey")
    	}
    }
    
  	try {
      
      	var TSD = TriggeredSend.Init(Platform.Variable.GetValue("@TriggeredSendExternalKey"));
		var Status = TSD.Send(data.subscriber,data.attributes);
      
      	if(Status != "OK") {
   			Write("(!) Error: " + Stringify(Status));
		} else {
        	Write("(+) Great success!");
        }
      
    } catch(err) {
     	
		Write("(!) Error: " + Stringify(err));
      
    }
    
</script>

How to pre-fill a form with AMPscript

Not enough info? Jump to the article.

From URL parameters

%%[
	SET @FirstName = QueryParameter('fname')
	SET @LastName = QueryParameter('lname')
]%%
<form>
	<input name="fname" value="%%=v(@FirstName)=%%" type="text" placeholder="First name">
	<input name="lname" value="%%=v(@LastName)=%%" type="text" placeholder="Last name">
	<button>Submit</button>
</form>

From Data Extension

%%[
	SET @Id = QueryParameter('id')
	SET @Rows = LookupRows('DataSource','Customer ID',@Id)
	IF ROWCOUNT(@Rows) > 0 THEN
		SET @FirstName = FIELD(ROW(@Rows,1),'First name')
		SET @LastName = FIELD(ROW(@Rows,1),'Last name')
	ENDIF
]%%
<form>
	<input name="fname" value="%%=v(@FirstName)=%%" type="text" placeholder="First name">
	<input name="lname" value="%%=v(@LastName)=%%" type="text" placeholder="Last name">
	<button>Submit</button>
</form>

From Salesforce object

%%[
	SET @Id = QueryParameter('id')
	SET @Rows = RetrieveSalesforceObjects('Contact', 'FName, LName', 'CustomerID', '=', @Id)
	IF ROWCOUNT(@Rows) > 0 THEN
		SET @FirstName = FIELD(ROW(@Rows,ROWCOUNT(@Rows)),'FName')
		SET @LastName = FIELD(ROW(@Rows,ROWCOUNT(@Rows)),'LName')
	ENDIF
]%%
<form>
	<input name="fname" value="%%=v(@FirstName)=%%" type="text" placeholder="First name">
	<input name="lname" value="%%=v(@LastName)=%%" type="text" placeholder="Last name">
	<button>Submit</button>
</form>

How to claim a Coupon Code with AMPscript

Not enough info? Jump to the article.

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <title>Get my coupon code</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <pre>%%[

        SET @SubscriberKey = RequestParameter("k")
        SET @Submitted = RequestParameter("v")
        SET @Now = SystemDateToLocalDate(Now())

        IF NOT EMPTY(@SubscriberKey) THEN

            Outputline(concat("SubscriberKey is ",@SubscriberKey))

            SET @CouponCode = Lookup('CouponCodesDE','CouponCode','SubscriberKey',@SubscriberKey)

            IF EMPTY(@CouponCode) THEN

                Outputline(concat("Subscriber doesn't have a CouponCode"))
				
                SET @CouponCode = GUID()

                Outputline(concat("Generating the CouponCode: ",@CouponCode))

                UpsertDE('CouponCodesDE', 1, 'SubscriberKey', @SubscriberKey, 'CouponCode', @CouponCode)

                Outputline(concat("Updating the Subscriber with the generated CouponCode"))

            ELSE

                Outputline(concat("Subscriber has a CouponCode: ",@CouponCode)) 

                SET @IsClaimed = Lookup('CouponCodesDE','IsClaimed','SubscriberKey',@SubscriberKey)    

                IF EMPTY(@IsClaimed) OR @IsClaimed != "True" THEN

                    Outputline(concat("Subscriber didn't claim his CouponCode"))

                    IF @Submitted == 1 THEN

                        UpsertDE('CouponCodesDE', 1, 'SubscriberKey', @SubscriberKey, 'IsClaimed', 'True', 'ClaimedDate', @Now)

                        Outputline(concat("CouponCode has been claimed by the Subscriber on ",@Now))

                    ENDIF

                ELSE

                    Outputline(concat("Subscriber has claimed his CouponCode"))    

                ENDIF

            ENDIF

        ELSE

            Outputline(concat("No SubscriberKey found."))      

        ENDIF
        
    ]%%</pre>

    %%[ IF NOT EMPTY(@SubscriberKey) AND @Submitted != 1 THEN ]%%

    <form>
        <input name="k" type="hidden" value="%%=v(@SubscriberKey)=%%">
        <input name="v" type="hidden" value="1">
        <button>Claim my coupon code</button>
    </form>

    %%[ ELSEIF NOT EMPTY(@SubscriberKey) AND @Submitted == 1 THEN ]%%

        <p>Your coupon code is: %%=v(@CouponCode)=%%</p>

    %%[ ELSE ]%%

        <p>These are not the droids you are looking for.</p>

    %%[ ENDIF ]%%

</body>
</html>

How to create and move to folders with server-side Javascript

Not enough info? Jump to the article.

<script runat=server>

    Platform.Load("core","1.1");

    var DE = Folder.Retrieve({Property:"ContentType",SimpleOperator:"equals",Value:"dataextension"});
    var ParentFolderID = DE[0].ID;

    var newFolder = {
        "Name" : "Brand New Folder",
        "CustomerKey" : Platform.Function.GUID(),
        "Description" : "My new awesome folder",
        "ContentType" : "dataextension",
        "IsActive" : "true",
        "IsEditable" : "true",
        "AllowChildren" : "false",
        "ParentFolderID" : ParentFolderID
    }

    try {

        var Status = Folder.Add(newFolder);
        
        if(Status == 'OK') {
            Write('(+) Folder "' + newFolder.Name + '" was created successfully.' + '<br>')
        } else {
            Write('(!) Folder "' + newFolder.Name + '" was not created. Error message: ' + Status + '<br>')
        }

    } catch(err) {
        Write('(!) Folder "' + newFolder.Name + '" was not created. Error message: ' + err + '<br>')
    }

</script>
<script runat=server>

    Platform.Load("core","1.1");

    var DataExtensionCustomerKey = "SampleDEkey",
        TargetFolderName = "Brand New Folder";

    var TargetFolderProperties = Folder.Retrieve({ Property: "Name", SimpleOperator: "equals", Value: TargetFolderName });
    var TargetFolderFolderID = TargetFolderProperties[0].ID;  

    var DE = DataExtension.Init(DataExtensionCustomerKey);
    var obj = {
        CategoryID : TargetFolderFolderID 
    }
    
    try {

        var Status = DE.Update(obj);

        if(Status == 'OK') {
            Write('(+) Data Extension "' + DataExtensionCustomerKey + '" was moved to "' + TargetFolderName + '" folder successfully.' + '<br>')
        } else {
            Write('(!) Data Extension "' + DataExtensionCustomerKey + '" was not moved to "' + TargetFolderName + ' folder. Error: ' + Status + '<br>')
        }
        
    } catch(err) {
        Write('(!) Data Extension "' + DataExtensionCustomerKey + '" was not moved to "' + TargetFolderName + ' folder. Error: ' + err + '<br>')
    }

</script>

How to create links and redirects with URL parameters

Not enough info? Jump to the article.

<a href="%%=RedirectTo(CONCAT(CloudPagesURL(1234,'color','blue')))=%%"></a>

How to read data from a Data Extension with server-side Javascript

Not enough info? Jump to the article.

<form>
    <label for="Options">List of options</label>
    <select name="Options">
        <option></option>
        <script runat="server">
            Platform.Load("core","1.1");
			var DE = "ListOfOptions"
            try {

                var ListOfOptionsDE = DataExtension.Init(DE);
                var Rows = ListOfOptionsDE.Rows.Retrieve();

                if (Rows.length > 0) {
                    for(var i in Rows) {
                        Write("<option>" + Rows[i]["Option"] + "</option>");
                    }
                }

                Variable.SetValue("rowMessage","(+) New data was retrieved successfully.");

            } catch (err) {
                Variable.SetValue("rowMessage","(-) No data was retrieved." + err);
            }
        </script>
    </select>
    <button>Submit</button>
</form>

How to debug AMPscript 

Not enough info? Jump to the article.

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

Send a Triggered Send email with AMPscript

Not enough info? Jump to the article.

%%[

/* =======================================================================
    
SEND A TRIGGERED SEND EMAIL

Before starting:

- Create an email
- Create a data extension from a template TriggerSendDataExtension
- Create a TriggerSend message using the previously created email and data extension
- Copy the TriggerSend external key

=========================================================================== */

/* Data */
SET @SubscriberKey = Format(SystemDateToLocalDate(NOW()), "yyddMMhhmmss")
SET @EmailAddress = "misterblue@mail.com"
SET @Language = "EN"
SET @TriggerSendExternalKey = "12345"

IF NOT EMPTY(@TriggerSendExternalKey) THEN

    /* Specify the external key of the TriggerSend */
    SET @TriggerSend = CreateObject("TriggeredSend")
    SET @TriggerSendDefinition = CreateObject("TriggeredSendDefinition")
    SetObjectProperty(@TriggerSendDefinition, "CustomerKey", @TriggerSendExternalKey)
    SetObjectProperty(@TriggerSend, "TriggeredSendDefinition", @TriggerSendDefinition)

    /* Specify the email address and the subscriber key */
    SET @TriggerSendSubscriber = CreateObject("Subscriber")
    SetObjectProperty(@TriggerSendSubscriber, "EmailAddress", @EmailAddress) 
    SetObjectProperty(@TriggerSendSubscriber, "SubscriberKey", @SubscriberKey) 

    /* Fill out the Language field in the TriggerSend data extension */
    SET @TriggerSendLanguage = CreateObject("Attribute")
    SetObjectProperty(@TriggerSendLanguage, "Name", "Language")
    SetObjectProperty(@TriggerSendLanguage,"Value", @Language)
    AddObjectArrayItem(@TriggerSend, "Attributes", @TriggerSendLanguage)

    /* Fill out the FirstName field in the TriggerSend data extension */
    SET @TriggerSendFirstName = CreateObject("Attribute")
    SetObjectProperty(@TriggerSendFirstName, "Name", "FirstName")
    SetObjectProperty(@TriggerSendFirstName,"Value", @FirstName)
    AddObjectArrayItem(@TriggerSend, "Attributes", @TriggerSendFirstName)

    AddObjectArrayItem(@TriggerSend, "Subscribers", @TriggerSendSubscriber)  
    
    /* Send the email */
    SET @TriggerSend_statusCode = InvokeCreate(@TriggerSend, @TriggerSend_statusMsg, @errorCode) 

    /* Error log */
    IF @TriggerSend_statusCode != "OK" THEN
       OUTPUTLINE(CONCAT("Status: ",@TriggerSend_statusMsg," / Code: ",@errorCode))
    ENDIF

ENDIF

/* =======================================================================

NOTES

1. TriggerSend_statusCode will return "OK" if the message has been successfully sent.
2. If the email did not arrive, please check if the TriggerSend is Active or if the contact is not blacklisted.

=========================================================================== */

]%%

Create a Data Extension with server-side Javascript

Not enough info? Jump to the article.

<script runat="server">

    /* =======================================================================
        
    CREATE A DATA EXTENSION WITH SSJS

    What it does:

    - Create a Data Extension named "MyDataExtension" with 3 fields: Id, MyData and Active
    - Delete every record from this Data Extension where Active = True
    - Create a new record where Id = 1, MyData = "Quick brown fox" and Active = True
    - Create a new record where Id = 2, MyData = "Big white bear" and Active = True

    =========================================================================== */

    Platform.Load("core","1.1");

    var DE = "MyDataExtension"

    /* Create a new Data Extension */
    try {
        var obj = {
            "CustomerKey" : Platform.Function.GUID(),
            "Name" : DE,
            "Fields" : [
                { "Name" : "Id", "FieldType" : "Number", "IsPrimaryKey" : true, "IsRequired" : true },
                { "Name" : "MyData", "FieldType" : "Text", "MaxLength" : 50 },
                { "Name" : "Active", "FieldType" : "Boolean", "DefaultValue" : true }
            ]
        };
        DataExtension.Add(obj);
        Write("(+) Data Extension was created successfully." + "<br>");
    } catch (err) {
        Write("(!) Data Extension was not created. Error message: " + err + "<br>")
    }     

    /* Deleting old data */     
    try {
		var deleteDE = DataExtension.Init(DE);
		deleteDE.Rows.Remove(["Active"],["True"]);
		Write("(+) Old records were deleted." + "<br>");
	} catch(e) {
		Write("(!) No old records were deleted: " + e + "<br>");
	}

    /* Insert new data */
    try {
        Platform.Function.InsertData(DE,["Id","MyData","Active"],["1","Quick brown fox","True"]);
        Platform.Function.InsertData(DE,["Id","MyData","Active"],["2","Big white bear","True"]);
        Write("(+) New data was inserted successfully." + "<br>");
    } catch(err) {
        Write("(!) New data was not inserted. Error message: " + err + "<br>");
    }  

</script>

Secure Cloud pages

Not enough info? Jump to the article.

<!DOCTYPE html>
<html>
<head>
  <meta name="ROBOTS" content="NOINDEX, NOFOLLOW">
</head>
<body>
%%[
    SET @origin = HTTPRequestHeader("Referer")
    SET @pattern = "^(https:\/\/(.*\.)?((example)\.com))($|\/)"
    SET @match = RegExMatch(@origin, @pattern, 1)
]%%
<script runat=server>
    Platform.Load("core","1");
    var MATCH = Variable.GetValue("@match");
    if (!MATCH) { MATCH = null }
    HTTPHeader.SetValue("Access-Control-Allow-Methods","POST");
    HTTPHeader.SetValue("Access-Control-Allow-Origin",MATCH);
    Platform.Response.SetResponseHeader("Strict-Transport-Security","max-age=200"); 
	Platform.Response.SetResponseHeader("X-XSS-Protection","1; mode=block"); 
	Platform.Response.SetResponseHeader("X-Frame-Options","Deny"); 
	Platform.Response.SetResponseHeader("X-Content-Type-Options","nosniff"); 
	Platform.Response.SetResponseHeader("Referrer-Policy","strict-origin-when-cross-origin"); 
	Platform.Response.SetResponseHeader("Content-Security-Policy","default-src 'self'"); 
</script>
%%[

IF LENGTH(@match) > 0 THEN

/* my ampscript code */

ENDIF 

]%%
</body>

Have I missed anything?

Too bad! Well, you can still use the contact form to contact me and tell me how wrong I am.