Can't figure out why after my ajax addToCart function is called not being redirected to cart?
The product is getting into cart as expected.
I have tried preventingDefault and not preventing.
Here is what response and formData look like in image below.
Here is my product form.
<div >
<h2 >Your Selections</h2>
{% assign product_form_id = 'product-form-' | append: section.id %}
{%- form 'product',
product,
id: product_form_id,
class: 'form',
novalidate: 'novalidate',
data-type: 'add-to-cart-form'
-%}
<input
type="hidden"
name="id"
value="{{ product.selected_or_first_available_variant.id }}"
disabled
>
<div >
<button
type="submit"
@click.prevent="addToCart(items, box_size)"
:
>
<p x-show="!full_box">
<span x-text="items_selected" ></span><span >of</span
><span x-text="box_size"></span><span >Selected</span>
</p>
<p x-show="full_box" >Add to cart</p>
</button>
</div>
{%- endform -%}
</div>
Here is my addToCart function.
<div
x-data="
{
addToCart(items, size){
const price = getBoxPrice(size)
console.log({price})
let itemsToAdd = items.map((item) => {
return item['title'];
})
let selectedItems = itemsToAdd.toString()
console.log({selectedItems})
console.log({itemsToAdd})
let formData = {
'items': [{
'id': 44202123100470,
'quantity': 1,
'properties': {
'Box Items': selectedItems,
}
}]
};
console.log({formData})
fetch(window.Shopify.routes.root 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
console.log(response)
return response.json();
})
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
reset()
}
}
"
> ....</div>
CodePudding user response:
The way I solved this was to use the Location API add location.href="/cart" in the success promise of the Ajax call.
fetch(window.Shopify.routes.root 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
console.log(response)
return response.json();
})
.then((data) => {
location.href = '/cart';
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});