Marketing cloud SSJS - javascript passing values between 2 scripts - javascript

I have a cloud pages.
On this page , i have
SSJS script , which retrives records from a data extension. From the count column in the data extension , i want to create a array like
dataarray = [10,20,30,40,50]
Then i need to pass this array (dataarray ) to another script where i can use it in d3.
The problem i am facing is how to pass values from a script which run at server to a script which run in client . I have tried hidden html element method which does not work and does not garrentte seq of script execution.
can you please advise how to pass values .
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="https://www.abc.nl/favicon.ico">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
</head>
<body>
<script runat="Server">
Platform.Load("core","1.1.5");
var data_rec;
try
{
var myDE = DataExtension.Init('01_Reporting_Sent_Today');
var filter = {Property:'return',SimpleOperator:'equals',Value:'1'};
var data = myDE.Rows.Retrieve(filter);
data_rec = data.length;
Write("<br/>The len is :" + Stringify(data_rec))
}catch(ex)
{
Write("<br/>The error is :" + Stringify(ex))
}
</script>
<script>
var datachart = [10,20,30,40,50];
var canvas = d3.select("body")
.append("svg")
.attr("width",500)
.attr("height",500)
var bars = canvas.selectAll("rect")
.data(datachart)
.enter()
.append("rect")
.attr("width",function (d) { return d;})
.attr("height",50);
</script>
</body>
</html>
so the dataarray from first script , i need to use in second script

You can use AMPScript to return the value inside the JS script:
Update: fixed incorrect syntax in my example as pointed out by Reidenshi
<script runat="server">
...
var dataString = Stringify(data);
Variable.SetValue("#dataString", dataString);
</script>
<script>
var data = JSON.parse(%%=v(#dataString)=%%);
</script>

Related

Not able to render heatmap using heatmap.js

I want to make a project where I can display the different sensor values from differens sensors in a room on a heatmap. The sensor values are stored in a MySQL database, and I want to use the heatmap.js library for the visualisation of this heatmap.
I used an example project from the library creator himself, but I am not able to render it and I just see my header and footer. What am I doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
</head>
<body>
<?php
include_once ('header.php');
?>
<main>
<script src="heatmap.js"></script>
<div class="heatmap"></div>
<script>
// minimal heatmap instance configuration
var heatmapInstance = h337.create({
// only container is required, the rest will be defaults
container: document.querySelector('.heatmap')
});
// now generate some random data
var points = [];
var max = 0;
var width = 840;
var height = 400;
var len = 200;
while (len--) {
var val = Math.floor(Math.random()*100);
max = Math.max(max, val);
var point = {
x: Math.floor(Math.random()*width),
y: Math.floor(Math.random()*height),
value: val
};
points.push(point);
}
// heatmap data format
var data = {
max: max,
data: points
};
// if you have a set of datapoints always use setData instead of addData
// for data initialization
heatmapInstance.setData(data);
</script>
</main>
<?php
include_once ('footer.php');
?>
</body>

How can I copy to clipboard specific part of paragraph?

I want to make the method or only copy to clipboard the "syntax" part of a paragraph.
I've done the logic to get the specific part of content I want and stored it in variable "syntaxClean". Now I just need to copy it somehow.
document.execCommand("copy"); would be awesome, but I just can't seem to make it work.
<!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>Test</title>
</head>
<body>
<pre id="test"></pre>
<script>
const message = "====== Executor details =======\nathena#21.109.21.25 (tunneled:39516)\n====== Request details ========\nClass....................: com.ericsson.athena.taf.os.linux.commands.common.SimpleCmdRequest\nThread : ................: main\nExpected prompt..........: ^((?![<?]|\\\\.{3}|(\\\\S+\\\\s){6,}).)*[>#$%]+(\\\\\\\\u001B\\\\[(\\\\d;?)*[m|n|K])*\\\\s(\\\\\\\\u001B\\\\[(\\\\d;?)*[m|n|K])*$|#\\\\s\\\\u001B\\\\[6n\nPrompt forced............: false\nTimeout..................: 20000ms\nSyntax...................: lsb_release -i\n"
document.getElementById("test").append(message);
var res = message.split("\n");
for (var i in res) {
if (res[i].indexOf("Syntax") != -1) {
var syntax = res[i].split(':');
var syntaxClean = syntax[1].slice(1);
console.log(syntaxClean);
}
}
</script>
</body>
</html>
In this example I would like to copy to clipboard "lsb_release -i" and I have it stored in variable syntaxClean as I've already said above.
Any help is appreciated!
You can achieve this by creating a dummy textarea like this:
<!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>Test</title>
</head>
<body>
<pre id="test"></pre>
<button onclick="copy()">Copy</button>
<script>
const message = "====== Executor details =======\nathena#21.109.21.25 (tunneled:39516)\n====== Request details ========\nClass....................: com.ericsson.athena.taf.os.linux.commands.common.SimpleCmdRequest\nThread : ................: main\nExpected prompt..........: ^((?![<?]|\\\\.{3}|(\\\\S+\\\\s){6,}).)*[>#$%]+(\\\\\\\\u001B\\\\[(\\\\d;?)*[m|n|K])*\\\\s(\\\\\\\\u001B\\\\[(\\\\d;?)*[m|n|K])*$|#\\\\s\\\\u001B\\\\[6n\nPrompt forced............: false\nTimeout..................: 20000ms\nSyntax...................: lsb_release -i\n"
document.getElementById("test").append(message);
function copy() {
var res = message.split("\n");
for (var i in res) {
if (res[i].indexOf("Syntax") != -1) {
var syntax = res[i].split(':');
var syntaxClean = syntax[1].slice(1);
console.log(syntaxClean);
copyToClipboard(syntaxClean);
}
}
}
function copyToClipboard(text) {
var dummyElm = document.createElement("textarea");
document.body.appendChild(dummyElm);
dummyElm.value = text;
dummyElm.select();
document.execCommand("copy");
document.body.removeChild(dummyElm);
}
</script>
</body>
</html>

Search for word and color it

I am trying to search for a word in iframe and color it using angularjs and jquery. For jquery code i took help from #andrew stackoverflow.
In Jquery code if condition is there, controller is not going inside if condition. please help me to solve the problem.
Here is my complete code, which contains angular code and jquery code.
Angular code is working just fine, in the console i am able to see all the consoles, first i am parsing the arrays and taking out only the string required to search in the jquery. After that i am using that search word to search in the the iframe. But i am facing some problem with the jquery code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html ng-app="app">
<head>
<title>
<%=t itle %>
</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</head>
<body>
<div ng-controller="ToddlerCtrl">
<h2>Sample</h2>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script type="text/javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<iframe src="text.txt" id="myIframe"></iframe>
<script type="text/javascript">
var myApp = angular.module('app', []);
myApp.controller('ToddlerCtrl', function($scope) {
// Define an array of Toddler objects
$scope.toddlers = [
[100, ["sample"]],
[100, ["used"]],
[100, ["tag"]],
[33.33333333333334, ["file"]]
];
for (var key in $scope.toddlers) {
if ($scope.toddlers.hasOwnProperty(key)) {
var temp = JSON.stringify($scope.toddlers[key][1])
var final_string = temp.slice(2, -2);
var searchWord = final_string;
// console.log(searchWord)
$(document).ready(function() {
$('#myIframe').ready(function() {
var $html = $($('#myIframe').contents().find('body').html());
if ($html.contents().text().search(searchWord) != -1) {
// Some problem with the if condition i guess.
// Controller is not entering if condition.
var replaceWith = "<span style='color:red'>" + searchWord + "</span>"
var newHTML = $html.text().replace(searchWord, replaceWith);
$('#myIframe').contents().find('body').html(newHTML);
}
});
});
// alert($scope.toddlers[key][1]);
// console.log("searchWord")
}
}
});
You can do it easily with Jquery, you can use this function on Javascript:
function findAndColorWord(html, word, color){
var indexWordStart = html.indexOf(word);
var wordLength = word.length;
var coloredWord = '<span style="color: '+color+'">'+word+'</span>';
var firstHtmlPart = html.substring(0, indexWordStart - 1);
var secondHtmlPart = html.substring(indexWordStart + wordLength, html.length - 1);
return firstHtmlPart + coloredWord + secondHtmlPart;
}
You only need to get the position of the word in the html of the iframe, that you can get with $("#id-of the iframe")[0].outerHTML , and after insert in that position a span element with the colored style for the word.
I maked a basic example with a Div that works in the same way that with an a iframe, you can see the example here:
https://jsfiddle.net/9zt976uz/2/#&togetherjs=nQoh3LINQG

Firefox not executing JavaScript files that were loaded dynamically

I'm trying to load two scripts that were functionally deferred on account of their type attributes being non-standard i.e. text/javascript/defer. Doing this causes the parser to ignore them so I want to reload them using JavaScript.
My HTML is as below:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>No Title</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript/defer" src="assets/js/test3.js"></script>
<script type="text/javascript/defer" src="assets/js/test4.js"></script>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script>
$(document).ready(function(){
var defer_js_collection_obj = $("[type='text/javascript/defer']"),
el_head_rq_obj = $('head'),
el_head_obj = el_head_rq_obj[0]
;
if(defer_js_collection_obj.length > 0)
{
//Reload JavaScript
defer_js_collection_obj.each(function() {
var file_src_outer_html_str = this.outerHTML;
var file_src_res_arr = file_src_outer_html_str.match("src *\= *[\"\']{1}(.*?)[\"\']{1}");
var file_src_str = file_src_res_arr[1];
var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file_src_str);
document.getElementsByTagName("head")[0].appendChild(fileref);
});
//Unload JavaScript with defer tag
for(var j = defer_js_collection_obj.length-1; j >= 0; j--)
{
defer_js_collection_obj[j].parentNode.removeChild(defer_js_collection_obj[j]);
}
}
});
</script>
</head>
<body>
<div>Load Deferred JavaScript</div>
</body>
</html>
jquery.js is version 1.11.2. test3.js and test4.js reference the javascript files I want to load, and they contain console.log('test3.js is loaded'); and console.log('test4.js is loaded'); respectively.
The issue I'm having is that this script works virtually everywhere else except on Firefox. I'm on a Mac OS X 10.10.5 using Firefox 46.0.1, and I don't see the console.log message when I load the script.
How can I fix this?
It might be a mime type issue. Do you happen to see any message in the console stating "not well-formed"? In any case, this seemed to work for me and I agree that your code did not work in FF when I first tried it.
$(document).ready(function(){
console.log("main");
var $body = $($("body")[0]);
var $scripts = $("[type='text/javascript/defer']");
$scripts.each(function(){
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", $(this).attr("src"));
$body.append(scriptTag);
});
});
Try to append your script at the end of body, so instead do:
document.getElementsByTagName("body")[0].appendChild(fileref);

Clickstream Tracking in Veeva CRM

I am working with Veeva CRM, trying to use Click Stream Tracking. I have the code which I am using and trying to track the Presentation id, Product Key Message, track an Element Description and Answer.
Can anybody help with the code that I am using.
Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>CLM_CERT_HCPName</title>
<!-- Bootstrap -->
<link href="css/style.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<script src="js/veeva-library-3.0.js"></script>
<script>
function start(){
header_getAccountName();
}
function header_getAccountName(){ com.veeva.clm.getDataForCurrentObject("Account","Name",header_displayAccountName)}
function header_displayAccountName(result){
var AccountNameHTML = document.getElementById("hcpName");
AccountNameHTML.innerHTML += result.Account.Name;com.veeva.clm.getDataForCurrentObject("Presentation","Survey_vod__c",header_getSurveyID);
}
function mySaveObject(){
//This is the start of my JSON object
var myCallClickStream = {Call_vod__c, Key_Message_vod__c};
//i am using my JSON obj name with the field API name of the call clickstream object obj.apiName then set the value. obj.apiName= value;]
// Create the record using the com.veeva.clm.createRecord
com.veeva.clm.createRecord("Call_ClickStream_vod_c", myCallClickStream, printSavedResults)}
function printSavedResults(result){
alert(JSON.stingify(result));
}
</script>
</head>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
I have also some sample code to try out but not sure what I am doing wrong.
function mySaveObject(){
var myCallClickStream = {};
myCallClickStream.Text_Entered_vod__c = "i will put some text here";
com.veeva.clm.createRecord("Call_Clickstream_vod__c", myCallClickStream, printSavedResults)
}
function printSavedResults(result) {
alert(JSON.stringify(result));
}
Not sure if you still need help on this or not. But my team uses a simple method in every project to simplify the tracking process. The below was modified to fit some of your naming conventions/needs.
// clmDescription - string submitted as the description to be tracked
// clmAnswer - string submitted as the answer to be tracked`
// callback - call back function which will be used to return the information
function mySaveObject( clmDescription, clmAnswer, clmCallback ) {
var url = window.location.pathname,
filename = url.substring(url.lastIndexOf('/') + 1),
clmTrackingID = filename.replace(".html", "");
var myCallClickStream = {};
myCallClickStream.Track_Element_Id_vod__c = clmTrackingID;
myCallClickStream.Track_Element_Type_vod__c = clmDescription;
myCallClickStream.Selected_Items_vod__c = clmAnswer;
myCallClickStream.Track_Element_Description_vod__c = clmAnswer;
// var myJSONText = JSON.stringify( myCallClickStream );
com.veeva.clm.createRecord( Call_Clickstream_vod__c, myCallClickStream, clmCallback );
}
Simply call the method and pass in your parameters, including your callback method.
Hope this helps!

Categories

Resources