Intermittent add to cart function

Highlighted
New Member
1 0 0

Hi,

I have this BOGO setup wherein a customer can buy an item and get a different item for free/discounted price. I have no problem here. What I want is once a customer add a product, it will automatically add the discounted product in the cart by just a single tap of the add to cart button. I followed different methods using the ajax API. I can even see that it's working but the thing is this function goes on and off(intermittent)-- it will add both product but sometimes just one product.


variantIdMain = 37543245971634;
variantIdFree = 28501520089181;
addedQty = parseInt($("form input[name=quantity]").val()); // the quantity of the main product
let formData = {
'items': [{
    'id': variantIdMain,
        'quantity': addedQty
},
    {
'id': variantIdFree,
        'quantity': addedQty
    }]
};
fetch('/cart/add.js', {
method: 'POST',
    headers: {
    'Content-Type': 'application/json'
    },
    body: JSON.stringify(formData)
})
.then(response => {
console.log(response.json());
})
.catch((error) => {
console.error('Error:', error);
});
 
I have tried this one too for the free product:
 
$.get("/cart/37533673717938:1", function(data, status){
console.log("Data: " + data + "\nStatus: " + status);
});

The thing with that script is: Yes, it will add the free product automatically but will not continue with the main order form function(it will not add the main product).
 

I have tried this one too but still got same result(sometimes it works(auto add both products), other times not(just adds one of the two products)):
// added Quantity
          addedQty = parseInt($("form input[name=quantity]").val());
         
          currProdVariantId = 37543245971634;
          freeVariantId = 28501520089181;
          jQuery.post('/cart/add.js', {
              items: [
                {
                  id: freeVariantId,
                  quantity: addedQty                  
                },
                {
                  id: currProdVariantId,
                  quantity: addedQty
                }                
              ]
            })
            .done(function( data ) {
              console.log( data );
            });

I hope someone can help me, as I ran out of ideas how to solve this. Took me a lot time already just for this issue. Thanks in advance.
0 Likes