JavaScript Substr Google Tagmanager - javascript

I am trying to figure out how to strip the last 4 characters using a Google Tagmanager Macro function.
the CookieLanguage var is defined in another Google Tag that reads a string from a cookie. This sting contains data similar to: 'kjhooij;lpuououpo-9999' and I need to capture the last 4 characters.
function() {
try {
var cookie = {{CookieLanguage}}.substr(CookieLanguage.length - 4);
return cookie[0];
} catch(e) {
console.log("No cookie found");
return "n/a";
}
}
Somehow my cookie var remains empty, am I missing something?

Try this instead:
function() {
try {
var cookieLanguage = {{CookieLanguage}},
cookie = cookieLanguage.substr(cookieLanguage.length - 4);
return cookie[0];
} catch(e) {
console.log("No cookie found");
return "n/a";
}
}

Related

UrlFetchApp.fetch() skip on empty cell

I've written a script that gets an image url from a cell in Google Sheets and adds that image to a template in Google Docs. However, when the cell is empty, the script crashes:
var beforePhoto1 = UrlFetchApp.fetch(row[14]).getBlob();
Really new to programming and would appreciate anyones help as to how to prevent the above code from crashing in the event a cell is empty
Usually there are two options:
Check the value before:
if (row[14] != '') {
var beforePhoto1 = UrlFetchApp.fetch(row[14]).getBlob();
} else {
console.log('row[14] was empty');
var beforePhoto1 = 'default_value';
}
// rest code
Try to use the value and skip any error with try/catch:
try {
var beforePhoto1 UrlFetchApp.fetch(row[14]).getBlob();
} catch(e) {
console.log('row[14] was empty');
var var beforePhoto1 = 'default_value';
}
// rest code

Dynamics CRM 2016 Javascript forEach not supported

So I am trying to write javascript code for a ribbon button in Dynamics CRM 2016 that will grab a phone number from a list of Leads that can be seen in the Active Leads window.
However, when I try to run it, I get an error telling me
As I step into my code (I'm debugging), I see this error
Here is the code I am working with.
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
// this should iterate through the list
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
//this should get the id and name of the selected lead
getPhoneNumber(selected, SelectedEntityTypeName);
});
}
//I should have the lead ID and Name here, but it is returning null
function getPhoneNumber(id, entityName) {
var query = "telephone1";
Sdk.WebApi.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
// I'm trying to capture the number and display it via alert.
alert(telephone1);
},
function (error) {
alert(error);
})
}
Any help is appreciated.
What you have is an javascript error. In js you can only use forEach on an array. SelectedControlSelectedItemIds is an object not an array.
To loop though an object, you can do the following.
for (var key in SelectedControlSelectedItemIds){
if(SelectedControlSelectedItemIds.hasOwnProperty(key)){
getPhoneNumber(SelectedControlSelectedItemIds[key], SelectedEntityTypeName)
}
}
Okay, so I figured it out. I had help, so I refuse to take full credit.
First, I had to download the SDK.WEBAPI.
I then had to add the webAPI to my Javascript Actions in the Ribbon Tool Bench.
Then, I had to create a function to remove the brackets around the
SelectedControlSelectedItemIds
Firstly, I had to use the API WITH the forEach method in order for it to work.
These are the revisions to my code.
function removeBraces(str) {
str = str.replace(/[{}]/g, "");
return str;
}
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
//alert(SelectedEntityTypeName);
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
getPhoneNumber(removeBraces(selected), SelectedEntityTypeName);
// alert(selected);
});
}
function getPhoneNumber(id, entityName) {
var query = "telephone1";
SDK.WEBAPI.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
formatted = telephone1.replace(/[- )(]/g,'');
dialready = "1" + formatted;
withcolon = dialready.replace(/(.{1})/g,"$1:")
number = telephone1;
if (Xrm.Page.context.getUserName() == "Jerry Ryback") {
url = "http://111.222.333.444/cgi-bin/api-send_key";
} else if(Xrm.Page.context.getUserName() == "Frank Jane") {
url = "http://222.333.444.555/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bob Gilfred"){
url = "http://333.444.555.666/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Cheryl Bradley"){
url = "http://444.555.666.777/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bill Dunny"){
url = "http://555.666.777.888/cgi-bin/api-send_key";
}
if (url != "") {
var params = "passcode=admin&keys=" + withcolon + "SEND";
var http = new XMLHttpRequest();
http.open("GET", url + "?" + params, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
}
},
function (error) {
// alert(error);
})
}
To elaborate, once I successfully get the number, I remove the parenthesis, dashes and white-space. Then, I add a "1" to the beginning. Finally, I insert colons in between each number. Then, I create an HTTP command and send it to the office phone of whoever is using CRM at the time. The user eval and HTTP message is my code. I'm showing you all of this because it was a great learning experience, and this feature really adds to the functionality.
I hope some of you find this useful.
Thanks for the help.

Do math on JSON data

I'm currently trying to do some maths on my json data. But it's not doing what I want. I made a loop so the calculation apples to every row (by the way I work with angularJS)
Here's the part of my code where I'm trying to process the data :
angular.module('recordService', []).factory('recordService', ['$http', function($http) {
var url;
var recordService = [];
recordService.getAll = function(callback) {
url = "http://localhost/app/www/database/json.php";
$http({
url: url
}).then(function(rs) {
callback(rs.data);
function logArrayElements(element, index, array) {
var thdi = rs.data[index].THDI1_avg;
console.log(thdi + 5);
}
rs.data.forEach(logArrayElements);
}, function(err) {
console.log(err)
})
}
As you can see I trying to take one element from my array and add 5 to it (it's only a test; I want to do some more advanced math later). I can see in the console.log that's its not doing what I want.
For example, if my data is 10.25, I get 10.255 when I would like 15.25. Any ideas on what I'm doing wrong?
Thanks in advance
You need to convert the JSON data into a number as #epascarello has mentioned. JSON is serialized as strings.
function logArrayElements(element, index, array) {
var thdi = Number(rs.data[index].THDI1_avg);
console.log(thdi + 5);
}
The reason you get 10.255 is, because you are adding 5 to a string.
Try:
console.log(parseFloat(thdi) + 5);
Update regarding Not a Number:
There are a couple of ways you could check whether the value is a number.
isNaN()
if(isNaN(thdi)) {
console.log("Not a number");
} else {
console.log("Is a number");
console.log(parseFloat(thdi) + 5);
}
try / catch
try{
console.log(parseFloat(thdi) + 5);
} catch(err) {
console.log("not a number");
}
Edit: Won't give desired result.
typeof
if(typeof thdi === 'number') {
console.log("Is a number");
console.log(parseFloat(thdi) + 5);
} else {
console.log("not a number");
}
Also see: How do you check that a number is NaN in JavaScript?
Note: if thdi is undefined, then isNaN() will throw an error. typeof will be able to deal with undefined.

API Key with colon, parsing it gives TypeError: forEach isn't a function

I'm trying to use New York Times API in order to get the Top Stories in JSON but I keep on getting a:
Uncaught TypeError: top.forEach is not a function
I feel like there's something wrong with the API key since it has : colons in the url. I even tried to encode it with %3A but it still doesn't work.
This is the basic url:
http://api.nytimes.com/svc/topstories/v2/home.json?api-key={API-KEY}
My function that grabs the data from the url:
```
function topStories(topStoriesURL) {
$.getJSON(topStoriesURL, function(top) {
top.forEach(function(data) {
link = data.results.url;
cardTitle = data.results.title;
if(data.results.byline == "") { postedBy = data.results.source; }
else { postedBy = data.results.byline; }
imgSource = data.results.media[0].media-metadata[10].url;
createCardElements();
});
});
}
I console.log(url) and when I click it inside Chrome console, it ignored the part of the key that comes after the colon. I've been debugging, but I can't seem to figure out the error.
Here is a version of the code that works.
function topStories(topStoriesURL) {
$.getJSON(topStoriesURL, function(data) {
if (data.error) {
alert('error!'); // TODO: Add better error handling here
} else {
data.results.forEach(function(result) {
var link = result.url,
cardTitle = result.title,
postedBy = result.byline == "" ? result.source : result.byline,
hasMultimedia = (result.multimedia || []).length > 0,
imgSource = hasMultimedia ? result.multimedia[result.multimedia.length - 1].url : null;
createCardElement(link, cardTitle, postedBy, imgSource);
});
}
});
}
function createCardElement(link, title, postedBy, imgSource) {
// create a single card element here
console.log('Creating a card with arguments of ', arguments);
}
topStories('http://api.nytimes.com/svc/topstories/v2/home.json?api-key=sample-key');
You are most likely going to need to do a for ... in loop on the top object since it is an object. You can not do a forEach upon on object the syntax would probably look like this:
function topStories(topStoriesURL) {
$.getJSON(topStoriesURL, function(top) {
for (var datum in top) {
link = datum.results.url;
cardTitle = datum.results.title;
if(datum.results.byline == "") { postedBy = datum.results.source; }
else { postedBy = datum.results.byline; }
imgSource = datum.results.media[0].media-metadata[10].url;
createCardElements();
});
});
}
Heres the documentation on for...in loops

use javascript to find parameter in url and then apply if then logic

I am trying to make my page perform an action only if it sees that a particular parameter is present in the url.
I essentially want the javascript code to do this:
consider an example page such as: http://www.example.com?track=yes
If a page loads that contains the parameter 'track' within the url, print 'track exists', else if the 'track' parameter doesn't exist print 'track does not exist'
This should work:
if (window.location.search.indexOf('track=yes') > -1) {
alert('track present');
} else {
alert('track not here');
}
Use something like the function from Artem's answer in this SO post:
if (getParameterByName('track') != '') {
alert ('run track');
}
It's not hard to split up the query string to find the relevant bits:
var path = location.substr(1), // remove ?
queryBits = path.split('&'),
parameters = {},
i;
for (i = 0 ; i < queryBits.length ; i++) {
(function() { // restrict keyval to a small scope, don't need it elsewhere
var keyval = queryBits[i].split('=');
parameters[decodeURIComponent(keyval[0])] = decodeURIComponent(keyval[1]);
}());
}
// parameters now holds all the parts of the URL as key-value pairs
if (parameters.track == 'yes') {
alert ('track exists');
} else {
alert ("it doesn't");
}
What you're looking for is called the Query String or Query Parameter. See this function to get it w/o the use of plugins like jQuery: How can I get query string values in JavaScript?
You can use the window.location.search property:
if(/(^|&)track(&|$)/.test(window.location.search.substring(1))) {
alert('track exists!');
} else {
alert('it doesn\'t...');
}

Categories

Resources