Hi all,
My client and I are trying to dynamically populate some arrays to be sent to Google Tag Manager, however for some reason the jQuery seems to be “combining” all of the pushed objects into a single object.
Here is the code that runs on the checkout page when the user deselects the email form:
//Fires when the email field is unfocused
$(document).on('blur', '#checkout-email', function() {
let allItems = [];
let ItemNames = [];
let totalAmount = $('#total_amount').text().replace('$','').replace('USD','').trim();
$(".w-commerce-commercecheckoutorderitemslist").each((index, element) => {
let productdiv = $(element);
let sku_text = productdiv.find(".product_sku").text();
let price_text = getNumber(productdiv.find(".checkout-order-price").text());
let product_text = productdiv.find(".w-commerce-commerceboldtextblock").text();
let qty = productdiv.find(".checkout-quantity").text();
let product_img = productdiv.find(".w-commerce-commercecartitemimage").attr('src');
allItems.push({
"SKU": sku_text,
"ProductName": product_text,
"Quantity": qty,
"ItemPrice": price_text,
"RowTotal": price_text * qty,
"ImageURL": product_img
});
ItemNames.push(product_text);
});
dataLayer.push({event: "klaviyo_started_checkout", klaviyoecommerce: {
cart: [{
"$value": totalAmount,
"ItemNames": ItemNames,
"CheckoutURL": window.location.protocol + "//" + window.location.host + "/checkout",
"Items": allItems
}]
}});
});
The expected output should be something like this:
~ Object:
{
event: "klaviyo_started_checkout",
klaviyoecommerce: {
cart: [
{
$value: "43.00",
ItemNames: [
"Sesame Bagel, Salt Bagel, Poppy Seed Bagel, Cream Cheese (8 oz)"
],
CheckoutURL: "https://chicagodeli.webflow.io/checkout",
Items: [
{
SKU: "baked-bagel-sesame-6",
ProductName: "Sesame Bagel",
Quantity: "1",
ItemPrice: 16,
RowTotal: 16,
ImageURL: "..."
},
{
SKU: "baked-bagel-salt-6",
ProductName: "Salt Bagel",
Quantity: "1",
ItemPrice: 16,
RowTotal: 16,
ImageURL: "..."
},
...
]
}
]
}
}
However the actual output looks like this:
~ Object:
{
event: "klaviyo_started_checkout",
klaviyoecommerce: {
cart: [
{
$value: "43.00",
ItemNames: [
"Sesame BagelSalt BagelPoppy Seed BagelCream Cheese (8 oz)"
],
CheckoutURL: "https://chicagodeli.webflow.io/checkout",
Items: [
{
SKU: "baked-bagel-sesame-6baked-bagel-salt-6baked-bagel-poppy-1packaged-creamcheese-8oz",
ProductName: "Sesame BagelSalt BagelPoppy Seed BagelCream Cheese (8 oz)",
Quantity: "1111",
ItemPrice: 16,
RowTotal: 17776,
ImageURL: "https://uploads-ssl.webflow.com/61cb304b7b8f322d7f64b9fb/61cb304b7b8f32e29864bbf0_sb-web-1.jpg"
}
]
}
]
}
}
Does anyone know why this is happening? I have tried to change the .push() calls to other methods such as .splice(), and $.merge() with temp arrays, but they all lead to the same issue.
Thanks!