Dawn theme update cart-drawer after adding product throught add.js

Dawn theme update cart-drawer after adding product throught add.js

Azis
Tourist
5 0 2

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),
        });
      }

 

  

Replies 5 (5)

Azis
Tourist
5 0 2

bump

styleshop27
Shopify Partner
30 0 2

Did you ever find a solution to this?

Azis
Tourist
5 0 2

I never found the solution, I switched the approach since this one didn't work.

MuhammadArish
Shopify Partner
1 0 1

$.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
Shopify Partner
7 0 1

Great thanks, it worked, i was searching for this from 36 hours. 

Asif