SSJS Platform

SSJS Platform
Home Page

Server-Side JavaScript (SSJS) Platform Functions

Write an SSJS code block to get atrribute values

<script runat="server">
  /*
   * Script Author: Shashi Prasad
   * Date: 10th Dec, 2024
   * Description: This script demonstrates the use of GetAttributeValue to retrieve values 
   * from different attributes or fields for a recipient in Marketing Cloud.
   */

  // GetAttributeValue: Returns the value from a specified attribute or sendable data extension field.

  // Profile attribute email address
  var contactEmail = Platform.Recipient.GetAttributeValue('EmailAddr');
  Platform.Response.Write("Contact Email: " + contactEmail + '<br/>');
  
  // Sendable data extension attribute
  var subscriberkey = Platform.Recipient.GetAttributeValue('UID');
  Platform.Response.Write("Subscriber Key: " + subscriberkey + '<br/>');
  
  // MID
  var memberId = Platform.Recipient.GetAttributeValue('memberid');
  Platform.Response.Write("Member ID: " + memberId + '<br/>');
  
  // BU Name
  var busName = Platform.Recipient.GetAttributeValue('Member_Busname');
  Platform.Response.Write("Business Name: " + busName + '<br/>');
  
  // Subscriber Key
  var subscriberKey = Platform.Recipient.GetAttributeValue('_subscriberkey');
  Platform.Response.Write("Subscriber Key: " + subscriberKey + '<br/>');
  
  // Job Id
  var jobId = Platform.Recipient.GetAttributeValue('jobid');
  Platform.Response.Write("Job ID: " + jobId + '<br/>');
</script>

Write an SSJS block to delete data from data extension

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script deletes rows from a specified Data Extension where the specified 
   * column values match the given criteria.
   */

  // Define the Data Extension name
  var deName = "Dataview_Bounce";

  // Define the column names and values to match for deletion
  var columnNames = ["SMTPCode"];
  var columnValues = [550];

  // Delete rows from the Data Extension
  var rows = Platform.Function.DeleteData(deName, columnNames, columnValues);

  // Output the result
  Platform.Response.Write("Rows Deleted: " + rows);
</script>
                            

Write an SSJS block to insert data from data extension

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script inserts data into a specified Data Extension with the provided column names
   * and values.
   */

  // Define the Data Extension name
  var deName = "Dataview_Sent";

  // Define the column names and values for insertion
  var columnNames = ["JobID", "ListID", "BatchID", "SubscriberID", "SubscriberKey", "EventDate"];
  var columnValues = [12345, 12345, 12345, 1234567890, "shashi@gmail.com", "11/29/2023"];

  // Insert rows into the Data Extension
  var rows = Platform.Function.InsertData(deName, columnNames, columnValues);

  // Output the result
  Platform.Response.Write("Rows Inserted: " + rows);
</script>
                            

Write an SSJS block to lookup a data extension

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script looks up a SubscriberKey in a specified Data Extension based on
   * the provided column names and values.
   */

  // Define the Data Extension name
  var deName = "Dataview_Bounce";

  // Define the column names and values for the lookup
  var columnNames = ["IsUnique", "BounceCategory"];
  var columnValues = [1, "Hard bounce"];

  // Lookup SubscriberKey in the Data Extension
  var subscriberKey = Platform.Function.Lookup(deName, 'SubscriberKey', columnNames, columnValues);

  // Output the result
  Platform.Response.Write("SubscriberKey: " + subscriberKey);
</script>
                            

Write an SSJS block to Lookup rows by sorting a row in a data extension

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script looks up rows in a specified Data Extension based on
   * the provided column names and values.
   */

  // Define the Data Extension name
  var deName = "Dataview_Bounce";

  // Define the number of rows to return
  var numRows = 0; // Change this value as needed

  // Define the column and direction to sort by
  var sortOrder = 'SubscriberKey ASC'; // Change this value as needed

  // Define the column names for the lookup
  var columnNames = ["IsUnique", "BounceCategory"];

  // Define the values to look up in the specified columns
  var columnValues = [1, "Hard bounce"];

  // Lookup rows in the Data Extension
  var dataRows = Platform.Function.LookupOrderedRows(deName, numRows, sortOrder, columnNames, columnValues);

  // Output the result
  if(dataRows && dataRows.length > 0) {
    for(var i=0; i<dataRows.length; i++) {
      Platform.Response.Write("SubscriberKey: " + dataRows[i]["SubscriberKey"] +  "<br/>");
      Platform.Response.Write("EventDate: " + dataRows[i]["EventDate"] +  "<br/>");
      Platform.Response.Write("============================================= <br/>");
    }
  }
</script>

                            

Write an SSJS block to Lookup rows in a data extension

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script looks up rows in a specified Data Extension based on
   * the provided column names and values.
   */

  // Define the Data Extension name
  var deName = "Dataview_Bounce";

  // Define the column names for the lookup
  var columnNames = ["IsUnique", "BounceCategory"];

  // Define the values to look up in the specified columns
  var columnValues = [1, "Hard bounce"];

  // Lookup rows in the Data Extension
  var dataRows = Platform.Function.LookupRows(deName,columnNames,columnValues);

  // Output the result
  if(dataRows && dataRows.length > 0) {
    for(var i=0; i<dataRows.length; i++) {
      Platform.Response.Write("SubscriberKey: " + dataRows[i]["SubscriberKey"] +  "<br/>");
      Platform.Response.Write("EventDate: " + dataRows[i]["EventDate"] +  "<br/>");
      Platform.Response.Write("============================================= <br/>");
    }
  }
</script>
                            

Write an SSJS block to update data into a data extension

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script updates rows in a specified Data Extension based on
   * the provided column filter names and values.
   */

  // Define the Data Extension name
  var deName = "Dataview_Bounce";

  // Define the column names and values for the filter
  var columnFilterNames = ["IsUnique", "BounceCategory"];
  var columnFilterValues = [1, "Hard bounce"];

  // Define the column names and values for the update
  var columnUpdateNames = ["JobID", "ListID"];
  var columnUpdateValues = [12345, 12345];

  // Update rows in the Data Extension
  var rowsUpdated = Platform.Function.UpdateData(deName,columnFilterNames, columnFilterValues,columnUpdateNames, columnUpdateValues);

  // Output the result
  Platform.Response.Write("Rows Updated: " + rowsUpdated);
</script>
                            

Write an SSJS block to upsert data into a data extension

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script updates rows in a specified Data Extension based on
   * the provided column filter names and values.
   */

  // Define the Data Extension name
  var deName = "Dataview_Bounce";

  // Define the column names and values for the filter
  var columnFilterNames = ["IsUnique", "BounceCategory"];
  var columnFilterValues = [1, "Hard bounce"];

  // Define the column names and values for the update
  var columnUpdateNames = ["JobID", "ListID"];
  var columnUpdateValues = [12345, 12345];

  // Update rows in the Data Extension
  var rowsUpdated = Platform.Function.UpsertData(deName,columnFilterNames, columnFilterValues,columnUpdateNames, columnUpdateValues);

  // Output the result
  Platform.Response.Write("Rows Updated: " + rowsUpdated);
</script>
                            

Write an SSJS block for date and time function

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script demonstrates the usage of Now, SystemDateToLocalDate, and LocalDateToSystemDate functions.
   */

   // Get the current system time
   var time = new Date();

   // Convert system time to local time
   var localTime = Platform.Function.SystemDateToLocalDate(time);

   // Convert local time back to system time
   var systemTime = Platform.Function.LocalDateToSystemDate(time);

  // Output the result
  Platform.Response.Write("Time: " + time + "\n");
  Platform.Response.Write("Local Time: " + localTime + "\n");
  Platform.Response.Write("System Time: " + systemTime + "\n");
</script>

                            

Write an SSJS block for Utility function

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script demonstrates the usage of Base64Encode, Base64Decode, GUID, IsEmailAddress, IsPhoneNumber, and MD5 functions.
   */

   // Define a normal string
   var normalStr = "Shashi";

   // Encode the string to Base64
   var encodedStr = Platform.Function.Base64Encode(normalStr);

   // Decode the Base64-encoded string
   var decodedStr = Platform.Function.Base64Decode(encodedStr);

   // Generate a random GUID
   var randomID = Platform.Function.GUID();

   // Check if the email address is valid
   var isEmailValid = Platform.Function.IsEmailAddress("shashi@example.com");

   // Check if the phone number is valid
   var isPhoneValid = Platform.Function.IsPhoneNumber("1234567890");

   // Calculate MD5 hash of the string
   var md5String = Platform.Function.MD5(normalStr, "UTF-8");

  // Output the result
  Platform.Response.Write("Normal String: " + normalStr + "\n");
  Platform.Response.Write("Encoded: " + encodedStr + "\n");
  Platform.Response.Write("Decoded: " + decodedStr + "\n");
  Platform.Response.Write("Random ID: " + randomID + "\n");
  Platform.Response.Write("Is Email Valid: " + isEmailValid + "\n");
  Platform.Response.Write("Is Phone Valid: " + isPhoneValid + "\n");
  Platform.Response.Write("MD5 Hash: " + md5String + "\n");
</script>

                            

Write an SSJS block for ParseJSON function

<script runat="server">

  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1.1.1");

  // Your payload as a JSON string
  var payloadString = '[{"Prod_ID": 1, "Prod_Name": "Nike", "Prod_Desc": "Shoe"}, {"Prod_ID": 5, "Prod_Name": "Puma", "Prod_Desc": "Slipper"}, {"Prod_ID": 10, "Prod_Name": "Adidas", "Prod_Desc": "Jacket"}]';

  // Parse the JSON string
  var payload = Platform.Function.ParseJSON(payloadString);

  // Check if parsing was successful
  if (payload !== null) {

    // Iterate through the payload array
    for (var i = 0; i < payload.length; i++) {
      var product = payload[i];

      // Extract and print product details
      var productId = product.Prod_ID;
      var productName = product.Prod_Name;
      var productDescription = product.Prod_Desc;

      // Output the parsed values
      Platform.Response.Write("Product ID: " + productId + "<br>");
      Platform.Response.Write("Product Name: " + productName + "<br>");
      Platform.Response.Write("Product Description: " + productDescription + "<br>");
      Platform.Response.Write("-------------------------<br>");
    }

  } else {

    // Output message if parsing failed
    Platform.Response.Write("Failed to parse JSON.");

  }

</script>


                            

Write an SSJS block for browser utility function

<script runat="server">
  /*
   * Script Author: [Your Name]
   * Date: [Current Date]
   * Description: This script demonstrates the usage of various Platform.Request functions in Marketing Cloud scripting.
   */

   // Check if the request is made over SSL
   var IsSSL = Platform.Request.IsSSL;

   // Check if the request has SSL
   var HasSSL = Platform.Request.HasSSL;

   // Get the client's IP address
   var ClientIP = Platform.Request.ClientIP;

   // Get the request method (e.g., GET or POST)
   var Method = Platform.Request.Method;

   // Get the query string parameters
   var QueryString = Platform.Request.QueryString;

   // Get the referring URL
   var ReferrerURL = Platform.Request.ReferrerURL;

   // Get the current request URL
   var RequestURL = Platform.Request.RequestURL;

   // Get the user agent string
   var UserAgent = Platform.Request.UserAgent;

   // Get information about the browser
   var Browser = Platform.Request.Browser;

  // Output the result
  Platform.Response.Write("IsSSL: " + IsSSL + "\n");
  Platform.Response.Write("HasSSL: " + HasSSL + "\n");
  Platform.Response.Write("ClientIP: " + ClientIP + "\n");
  Platform.Response.Write("Method: " + Method + "\n");
  //Platform.Response.Write("QueryString: " + QueryString + "\n");
  //Platform.Response.Write("ReferrerURL: " + ReferrerURL + "\n");
 // Platform.Response.Write("RequestURL: " + RequestURL + "\n");
 // Platform.Response.Write("UserAgent: " + UserAgent + "\n");
 // Platform.Response.Write("Browser: " + Stringify(Browser) + "\n");
</script>
                            



Comments


Knowledge Article

Most Viewed

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Journey Builder REST API Documentation

Preference Center Demystified

Popular Posts

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Journey Builder REST API Documentation

Preference Center Demystified

SEND LOG EANBLEMENT

Share with Friends

Disclaimer:

The information provided on this technical blog is for general informational purposes only. As a SFMC (Salesforce Marketing Cloud) Technical Architect, I strive to offer accurate and up-to-date content related to SFMC and its associated technologies. However, please note that technology is constantly evolving, and the information provided may become outdated or inaccurate over time.

The content published on this blog represents my personal views and experiences as a SFMC Technical Architect and does not necessarily reflect the official views or opinions of any organization or employer I may be affiliated with.

While I make every effort to ensure the accuracy and reliability of the information presented, I cannot guarantee its completeness, suitability, or applicability to your specific circumstances. Therefore, it is essential to verify any information provided and make your own independent assessments or seek professional advice if needed.

Furthermore, any actions taken based on the information provided on this blog are at your own risk. I shall not be held liable for any damages, losses, or inconveniences arising from the use of the information presented here.

Please keep in mind that SFMC and its associated technologies are complex and require technical expertise for proper implementation and management. It is recommended to consult with qualified professionals or official SFMC documentation for comprehensive guidance.

Finally, please note that any product or company names mentioned on this blog are trademarks or registered trademarks of their respective owners. The mention of these trademarks or registered trademarks does not imply any endorsement or affiliation with the blog.

By accessing and using this blog, you agree to the terms of this disclaimer. If you do not agree with any part of this disclaimer, please refrain from using this blog.