Hi team,
I am building an app that displays two items in the cart. These two items can be added to the cart via an add to cart button. This is my liquid:
{% assign has_vaccine = false %}
{% for item in cart.items %}
{% if item.product.type == settings.cart_upsell_product_type %}
{% assign has_vaccine = true %}
{% endif %}
{% endfor %}
{% if has_vaccine %}
{% assign collection_to_display = collections[settings.cart_upsell_collection] %}
<span> {{ settings.cart_upsell_text }}</span>
{% for product in collection_to_display.products %}
<div class="product-item">
<div class="product-image">
<a href="{{ product.url }}">
<img src="{{ product.featured_image | img_url: 'medium' }}" alt="{{ product.title }}">
</a>
</div>
<div class="product-details">
<h2 class="product-title">
<a href="{{ product.url }}" class="product-link">{{ product.title }}</a>
</h2>
<p class="product-price">{{ product.price | money }}</p>
</div>
<form action="/cart/add.js" method="post" class="add-to-cart-form" data-variant-id="{{ product.variants.first.id }}">
<input type="hidden" name="id" value="{{ product.variants.first.id }}">
<button type="submit" class="btn add-to-cart-btn">Add to Cart</button>
</form>
</div>
{% endfor %}
{% endif %}
Then I have a js that:
document.addEventListener('DOMContentLoaded', function() {
// Function to add product to cart using AJAX
function addToCart(productId) {
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
id: productId,
quantity: 1
})
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Item added to cart:', data);
// Call the onCartUpdate method to refresh the cart drawer
const cartDrawerItemsInstance = document.querySelector('cart-drawer-items');
if (cartDrawerItemsInstance && typeof cartDrawerItemsInstance.onCartUpdate === 'function') {
cartDrawerItemsInstance.onCartUpdate();
}
})
.catch(error => {
console.error('Error adding item to cart:', error);
});
}
// Attach click event listener to all add-to-cart buttons
document.querySelectorAll('.add-to-cart-btn').forEach(button => {
button.addEventListener('click', function(event) {
event.preventDefault(); // Prevent the default form submission behavior
const form = this.closest('.add-to-cart-form');
const productId = form.getAttribute('data-variant-id');
addToCart(productId);
});
});
});
It seems to work as expected initially. However, every time that I remove an item from the cart, this form
<form action="/cart/add.js" method="post" class="add-to-cart-form" data-variant-id="{{ product.variants.first.id }}"> <input type="hidden" name="id" value="{{ product.variants.first.id }}"> <button type="submit" class="btn add-to-cart-btn">Add to Cart</button>
is executed and the handling of the event that I have in the js is bypassed. What could be happening?
Thank you!!!