Hi community!
I’m trying to implement a functionality in the cart of my site and I can’t get it to work 100%.
It consists in that if the user marks (or not) some radio buttons, some products are added to the cart after clicking on the checkout button. They are two radio buttons with two different products. The problem is that sometimes it adds only one, sometimes neither, and sometimes both, but it is not consistent in its operation.
The function I am using to add the product to the cart is this:
function agregarProductoAlCarrito(variant_id){
let data = {
'items':[{
'id': variant_id,
'quantity': 1
}]
};
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
return response.json();
})
.catch((error) => {
console.error('Error:', error);
});
}
To remove the product (if it is already in the cart):
function eliminarProductoDelCarrito(variant_id){
let data = {
'items':[{
'id': variant_id,
'quantity': 0
}]
};
fetch('/cart/change.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
return response.json();
})
.catch((error) => {
console.error('Error:', error);
});
}
Then on the onclick of the checkout button I do the following:
$(".custom-btn-checkout").click( function(e){
e.preventDefault();
if(radio1Si.checked){
agregarProductoAlCarrito({{ variant1_id }});
}
if(radio1No.checked){
eliminarProductoDelCarrito({{ variant1_id }});
}
if(radio2Si.checked){
agregarProductoAlCarrito({{variant2_id }});
}
if(radio2No.checked){
eliminarProductoDelCarrito({{ variant2_id }});
}
$(this).submit();
}
});
Could someone give me an idea of what might be going on? Perhaps it is something related to the execution time of the add and remove functions. I tried adding setTimeout to them but it doesn’t finish working 100%.
I would really appreciate if someone can give me some help.
Thanks!
