I am attempting to setup Data Layer variables on Google Tag Manager to capture ecommerce data for our site. I can successfully capture the id, name, price, and quantity for a single item; but if I want to setup GTM to handle an unknown amount of items, I always seem to get 'undefined' for the return value when Previewing my changes. Here is an example dataLayer custom event that triggers successfully:
dataLayer.push({
event: "AddToCart",
ecommerce: {
currency: "USD",
items: [
{
item_id: "CTFBK",
item_name: "Black Color Tissue Paper, 20x30\", Bulk 480 Sheet Flat Pack",
price: 35.75,
quantity: 1
},
{
item_id: "18WK",
item_name: "White Kraft Recycled Jewelry Boxes, 3.5x3.5x1\", 100 Pack, Fiber Fill",
price: 49.2,
quantity: 1
},
{
item_id: "RBLBC",
item_name: "Romantic Blooms Paper Gift Bag, Cub 8x4.75x10\", 250 Pack",
price: 125,
quantity: 3
}
]
},
gtm.uniqueEventId: 25
})
I created a DataLayer variable called 'ecommerce.items' that has the Data Layer Variable Name: 'ecommerce.items'. On Preview, this variable returns the below array:
[
{
item_id: "CTFBK",
item_name: "Black Color Tissue Paper, 20x30\", Bulk 480 Sheet Fla" +
"t Pack",
price: 35.75,
quantity: 1
},
{
item_id: "18WK",
item_name: "White Kraft Recycled Jewelry Boxes, 3.5x3.5x1\", 100 " +
"Pack, Fiber Fill",
price: 49.2,
quantity: 1
},
{
item_id: "RBLBC",
item_name: "Romantic Blooms Paper Gift Bag, Cub 8x4.75x10\", 250 " +
"Pack",
price: 125,
quantity: 3
}
]
This is the latest JavaScript function that I inserted into the 'Global Variable Name' for the JavaScript Variable that should return an array of price values:
function() {
var itemPrices = [];
var items = {{ecommerce.items}};
if (items && items.length > 0) {
for (var i = 0; i < items.length; i++) {
if (items[i].price) {
itemPrices.push(items[i].price);
}
}
}
return itemPrices;
}
According to the Variables tab in the GTM Preview, this returns 'undefined'. What can I do differently to return the array of prices for each item?
You can get dataLayer from global object window from JavaScript.
But maybe the problem with undefined it's that dataLayer is not set yet when you run your function and you always get undefined.