All things Shopify and commerce
Hello, I'm coding a bundle for displaying volume discounts, I currently got this code for handling the add to cart button:
const itemsToAdd = [];
const variantSelectors = selectorsContainer.querySelectorAll('.variant-selector');
variantSelectors.forEach((selector, index) => {
const variantId = selector.value;
itemsToAdd.push({
id: variantId,
quantity: 1,
/*properties: {
'Bundle': `${totalQuantity}-Pack Bundle`,
'Bundle Item': `${index + 1} of ${totalQuantity}`,
},*/
});
});
try {
const response = await fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ items: itemsToAdd }),
});
if (!response.ok) throw new Error('Add to cart failed');
window.location.href = '/cart';
} catch (error) {
console.error('Error adding to cart:', error);
alert('Error adding to cart. Please try again.');
}
}
}
It works, but I'm now sending people directly to the cart page, instead of just updating the cart drawer which the default add to cart button does. How can I update the cart drawer on the same way as the regular add to cart does, or is there a simpler way? Thanks
Hi @TrendBlend,
To update the cart drawer in a similar way as the regular add to cart button, you don't need to redirect the user to the cart page. Instead, you can use the Shopify Ajax API to update the cart drawer dynamically after adding the items to the cart.
Here’s an updated approach where you add the items to the cart and then update the cart drawer without redirecting the user:
const itemsToAdd = []; const variantSelectors = selectorsContainer.querySelectorAll('.variant-selector'); variantSelectors.forEach((selector, index) => { const variantId = selector.value; itemsToAdd.push({ id: variantId, quantity: 1, // You can uncomment the properties section if needed // properties: { // 'Bundle': `${totalQuantity}-Pack Bundle`, // 'Bundle Item': `${index + 1} of ${totalQuantity}`, // }, }); }); try { const response = await fetch(window.Shopify.routes.root + 'cart/add.js', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ items: itemsToAdd }), }); if (!response.ok) throw new Error('Add to cart failed'); // After adding items to cart, fetch the updated cart const updatedCart = await fetch(window.Shopify.routes.root + 'cart.js'); const cartData = await updatedCart.json(); // Update the cart drawer (example assuming you have a cart drawer element) const cartDrawer = document.querySelector('.cart-drawer'); // Adjust selector if needed const cartContent = document.querySelector('.cart-drawer-content'); // Adjust selector if needed if (cartDrawer && cartContent) { cartContent.innerHTML = ''; // Clear previous cart content // Loop through the cart data and update the cart drawer (you may need to adjust this) cartData.items.forEach(item => { const cartItem = document.createElement('div'); cartItem.classList.add('cart-item'); cartItem.innerHTML = ` <div class="cart-item-name">${item.quantity} x ${item.title}</div> <div class="cart-item-price">${Shopify.formatMoney(item.line_price)}</div> `; cartContent.appendChild(cartItem); }); // Optionally, update cart totals, item count, etc. const cartTotal = document.querySelector('.cart-total'); // Adjust selector if needed if (cartTotal) { cartTotal.textContent = Shopify.formatMoney(cartData.total_price); } // Open the cart drawer if it's closed (optional) cartDrawer.classList.add('open'); } } catch (error) { console.error('Error adding to cart:', error); alert('Error adding to cart. Please try again.'); }
This approach avoids redirecting users and keeps them within the same page while updating the cart drawer. You may need to adjust the element selectors (.cart-drawer, .cart-drawer-content, etc.) to match your theme.
Hello @CodingFifty , I got this code now:
async handleAddBundle(event) {
const selectedTier = this.container.querySelector('.volume-discount-tier.selected');
if (!selectedTier) {
alert('Please select a volume bundle first.');
return;
}
const tierQuantity = parseInt(selectedTier.dataset.quantity, 10);
const selectorsContainer = selectedTier.querySelector('.product-selectors-container') || selectedTier.querySelector('.tier-variants');
const totalQuantity = tierQuantity === 3 ?
parseInt(selectedTier.querySelector('.current-quantity').textContent, 10) :
tierQuantity;
const itemsToAdd = [];
const variantSelectors = selectorsContainer.querySelectorAll('.variant-selector');
variantSelectors.forEach((selector, index) => {
const variantId = selector.value;
itemsToAdd.push({
id: variantId,
quantity: 1,
/*properties: {
'Bundle': `${totalQuantity}-Pack Bundle`,
'Bundle Item': `${index + 1} of ${totalQuantity}`,
},*/
});
});
try {
const response = await fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ items: itemsToAdd }),
});
if (!response.ok) throw new Error('Add to cart failed');
// After adding items to cart, fetch the updated cart
const updatedCart = await fetch(window.Shopify.routes.root + 'cart.js');
const cartData = await updatedCart.json();
// Update the cart drawer (example assuming you have a cart drawer element)
const cartDrawer = document.querySelector('.cart-drawer'); // Adjust selector if needed
const cartContent = document.querySelector('.drawer__contents'); // Adjust selector if needed
if (cartDrawer && cartContent) {
cartContent.innerHTML = ''; // Clear previous cart content
// Loop through the cart data and update the cart drawer (you may need to adjust this)
cartData.items.forEach(item => {
const cartItem = document.createElement('div');
cartItem.classList.add('cart-item');
console.log(item);
console.log(item.title);
cartItem.innerHTML = `
<div class="cart-item__name">${item.quantity} x ${item.title}</div>
<div class="cart-item__discounted-prices">${Shopify.formatMoney(item.line_price)}</div>
`;
cartContent.appendChild(cartItem);
});
// Optionally, update cart totals, item count, etc.
/* const cartTotal = document.querySelector('.cart-total'); // Adjust selector if needed
if (cartTotal) {
cartTotal.textContent = Shopify.formatMoney(cartData.total_price);
}*/
// Open the cart drawer if it's closed (optional)
cartDrawer.classList.add('open');
}
//window.location.href = '/cart';
} catch (error) {
console.error('Error adding to cart:', error);
alert('Error adding to cart. Please try again.');
}
}
}
Which outputs these logs:
discounted_price: 3443discounts: (2) [{…}, {…}]featured_image: {aspect_ratio: 1, alt: 'GlowCurtain 1m x 1m LED lights with European plug for home decor.', height: 1600, url: 'https://cdn.shopify.com/s/files/1/0797/9833/7875/f…c6e0-cb87-4475-8a94-302e25c181f7.jpg?v=1734882643', width: 1600}final_line_price: 11475final_price: 3825gift_card: falsegrams: 0handle: "glowcurtain-400-led-lights"has_components: falseid: 49774845821267image: "https://cdn.shopify.com/s/files/1/0797/9833/7875/files/1_3_f4c4c6e0-cb87-4475-8a94-302e25c181f7.jpg?..."key: "49774845821267:1fa18bed6c0a5e8da23b0d6d7c1d50cf"line_level_discount_allocations: [{…}]line_level_total_discount: 2022line_price: 10327options_with_values: (2) [{…}, {…}]original_line_price: 13497original_price: 4499presentment_price: 44.99price: 4499product_description: "🌟 Transform Any Space! Create magical settings for at work, parties, cozy nights, or relaxing evenings.\n🎉 Easy Setup, Big Impact! Instantly elevate your décor with these glowing curtains."product_has_only_default_variant: falseproduct_id: 9599723635027product_title: "GlowCurtain: 400 LED Lights to Brighten Every Moment"product_type: ""properties: {}quantity: 3requires_shipping: truesku: nulltaxable: truetitle: "GlowCurtain: 400 LED Lights to Brighten Every Moment - 1M x 1M / Type A (EU)"total_discount: 3170url: "/nl/products/glowcurtain-400-led-lights?variant=49774845821267"variant_id: 49774845821267variant_options: (2) ['1M x 1M', 'Type A (EU)']variant_title: "1M x 1M / Type A (EU)"vendor: "TrendBlend"[[Prototype]]: Object
volume-discount-handler.js:241 GlowCurtain: 400 LED Lights to Brighten Every Moment - 1M x 1M / Type A (EU)
But I'm getting an error when I try to add the bundle to cart from: Glow Curtain: 400 LED Lights for a Magical Ambiance – InteriorGlows. I do not understand why I'm getting the error though, and also why nothing is being updated in the cart after clicking the add to cart button, because I have updated the selectors.
Hi @TrendBlend
try this code
const itemsToAdd = [];
const variantSelectors = selectorsContainer.querySelectorAll('.variant-selector');
variantSelectors.forEach((selector, index) => {
const variantId = selector.value;
itemsToAdd.push({
id: variantId,
quantity: 1,
/*properties: {
'Bundle': `${totalQuantity}-Pack Bundle`,
'Bundle Item': `${index + 1} of ${totalQuantity}`,
},*/
});
});
try {
const response = await fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ items: itemsToAdd }),
});
if (!response.ok) throw new Error('Add to cart failed');
// Dispatch custom event to trigger cart drawer update
document.dispatchEvent(new CustomEvent('cart:refresh', {
detail: { items: itemsToAdd }
}));
} catch (error) {
console.error('Error adding to cart:', error);
alert('Error adding to cart. Please try again.');
}
Hello @Ahmad31 , adding // Dispatch custom event to trigger cart drawer update document.dispatchEvent(new CustomEvent('cart:refresh', { detail: { items: itemsToAdd } })); did not do anything, thanks though
2m ago Learn the essential skills to navigate the Shopify admin with confidence. T...
By Shopify Feb 12, 2025Learn how to expand your operations internationally with Shopify Academy’s learning path...
By Shopify Feb 4, 2025Hey Community, happy February! Looking back to January, we kicked off the year with 8....
By JasonH Feb 3, 2025