javascript - Created "Buy X, Get Y Free" Script, How To Prevent Script From Running If Customer Removes Y?
Solution:
It is pretty simple. If you added the free item to the cart in the first place, you used a Javascript call to do that. So set your localStorage to have a key:value pair of something like "free": true.
Anytime you go to run your add this free thing to the cart, check if that key exists. If it does not, add the free thing. If it does exist, it means you already added a freebie to the cart, so don't do that again. If the customer chose to remove it, so be it, now it won't be re-added. You can then remove that key if you want on the way to checkout, or whatever... leave it.
Answer
Solution:
Taking from the answer posted above, here is what I was able to come up :
const params = { type: 'POST', url: '/cart/update.js', data: { updates: cartUpdates }, dataType: 'json', success: function(stuff) { window.location.href = '/cart'; // reloads to cart on successful post request } };
if(sessionStorage.getItem('itemInCart') === null ) {
jquery.ajax(params);
}
sessionStorage.setItem('itemInCart', 'true');
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.