Azis
December 3, 2023, 9:27am
1
As mentioned in the title I want to update the cart-drawer without refreshing the page just like the normal add does but I’m doing it with the add.js using this lines of code, how can I update the cart drawer? (stock dawn theme, no modifications):
const response = await fetch(window.Shopify.routes.root + 'cart/add.js', {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(products),
});
}
Did you ever find a solution to this?
Azis
December 30, 2023, 6:09pm
4
I never found the solution, I switched the approach since this one didn’t work.
$.ajax({
type: ‘POST’,
url: ‘/cart/add.js’,
data: JSON.stringify(data),
dataType: ‘json’,
contentType: ‘application/json’,
success: function(response) {
console.log(‘Product added to cart:’, response);
fetch(${routes.cart_url}?section_id=cart-drawer)
.then((response) => response.text())
.then((responseText) => {
const html = new DOMParser().parseFromString(responseText, ‘text/html’);
const selectors = [‘cart-drawer-items’, ‘.cart-drawer__footer’];
for (const selector of selectors) {
const targetElement = document.querySelector(selector);
const sourceElement = html.querySelector(selector);
if (targetElement && sourceElement) {
targetElement.replaceWith(sourceElement);
}
}
})
.catch((e) => {
console.error(e);
});
},
error: function(XMLHttpRequest, textStatus) {
console.error(‘Error adding product to cart:’, textStatus);
}
});
===================================================
[REDACTED]
Asif3
June 27, 2024, 5:08am
6
Great thanks, it worked, i was searching for this from 36 hours.