I have created a checkbox to add an item to the cart when checked, and removes from the cart when unchecked. The functionality works, the only issue is that it does not change until the page is reloaded. How can I make this instant? I have provided my validate function below (adds the item or removes it depending on checkbox status).
<script type="text/javascript">
function validate() {
if (document.getElementById('test').checked) {
let formData = {
'items': [{
'id': 45227867308341,
'quantity': 1
}]
};
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
return response.json();
})
.catch((error) => {
console.error('Error:', error);
});
} else {
let updates = {
45227867308341: 0
};
fetch(window.Shopify.routes.root + 'cart/update.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ updates })
})
.then(response => {
return response.json();
})
.catch((error) => {
console.error('Error:', error);
});
}
}
</script>
Which part do you mean by: “it does not change until the page is reloaded”
the item is either in the cart or not by that code if it’s working.
Do you mean change the html so the item is no longer in the list of line-item or it’s added to the line-items display?
Your choices are either
See the dawn reference theme and the cart item remove behavior for how section rendering is used in practice.
1 Like
When the checkbox is selected, the item is not added to the cart VISUALLY until the page is reloaded, or if I click on “add to cart” on the actual product of that product page (image below for reference). I want it to show in the cart immediately (it is in the cart but visually it does not update until reload). Sorry for the confusion, I worded it incorrectly.
Whichever theme your using all of this varies wildly among themes.
From the screenshot in most themes when using the addToCart button the cart display should visually update if there’s a cart notification or drawer for that products product form only.
If you have standalone code hitting the ajax api that runs AFTER using the AtC the theme has no way of what’s going on.
If it’s a cart-drawer/notification there is sometimes a rerender or open function that may fetch/refresh the contents of the drawer.
If you can edit the product form itself it may be saner to just adjust the product forms inputs to add both items to the cart when the AtC is used , off the top of my head I forget the format but basically find the variant id input and append brackets use brackets on the names to it and the additional items variant id input. e.g. 123456[]
{% example of regular product selectors name attribute bracketed for id parameter %}
{% example of additional product input name attribute bracketed for id parameter %}
1 Like
Optimally I’d like to have the cart update visually when the checkbox is clicked, similar to what happens when the add to cart button is pressed. I am using Dawn Theme with the Cart Drawer Feature. When an item is added to the cart via the add to cart button, the card drawer slides out from the right and displays the item in the cart (image below for reference- the keychain in the cart is what I’m working with for the checkbox at the moment, so the naming does not match). Is something like this possible? Perhaps there is a way to have the same result occur for when the checkbox is selected?
Maybe there is a way to update the cart drawer UI by using the JSON response without reloading the page?
“If it’s a cart-drawer/notification there is sometimes a rerender or open function that may fetch/refresh the contents of the drawer.”
I will try looking into this.
I found a solution that works using the cart notification version of the cart but I can’t find a way to do it with cart drawer (clicking the checkbox adds the keychain to the cart & causes the popup notification). I feel like this is close but I just need a way to do it with cart drawer. I have attached a screenshot of the cart notification method and the code below (protector variable is just a variant id):
const cartNotification = new CartNotification();
const config = fetchConfig('javascript');
config.headers['X-Requested-With'] = 'XMLHttpRequest';
config.body = JSON.stringify({
id: protector,
sections: cartNotification.getSectionsToRender().map((section) => section.id),
sections_url: window.location.pathname
});
fetch(`${routes.cart_add_url}`, config)
.then((response) => response.json())
.then((response) => {
cartNotification.renderContents(response);
})
.catch((e) => {
console.error(e);
});
It’s mainly in product-form.js you want to step through.
I think the cart-drawer doesn’t activate in the product-form when the cart-notification is enabled as it assigns the notification first:
this.cart = document.querySelector('cart-notification') || document.querySelector('cart-drawer');
But dawn may not have a direct method on the cart-drawer if they didn’t componentize the thing,it might not be rendering it the cart-notification component is enabled.
1 Like
Yea the CartNotification method only works when I toggle Popup notification instead of Drawer (image below). When Popup notification is toggled, the cart defaults to a page, not a drawer unfortunately. I will look into the methods within product-form.js and see if I can cause the visual cart update function to fire for the cart drawer for the checkbox add to cart .