I have created custom ajax add to cart functionality in my store and I want to open the slider cart after successful add to cart event. I have achieved it using the below code but it only works for the first time.
If you remove the products from cart and try to add again then it won't show the updated cart or if you want to add more to it then also it won't work. Cart drawer only opens for the first time only. I am using shopify flow theme.
function addProductsToCart(variantIdRegular, variantIdSubscription, selling_plan_id) {
var itemsToAdd = [{ id: variantIdRegular, quantity: 1 }];
if ($("input[name=payment-option]").is(":checked")) {
itemsToAdd.push({ id: variantIdSubscription, quantity: 1, selling_plan: selling_plan_id });
}
$.ajax({
url: '/cart/add.js',
type: 'post',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify({ 'items': itemsToAdd }),
success: function(response) {
console.log('Both products added', response);
var cartDrawerButtonSelector = ".js-drawer-open-right-link";
var cartDrawerButton = document.querySelector(cartDrawerButtonSelector);
cartDrawerButton.click();
},
error: function(xhr, status, error) {
console.error('Failed to add products', xhr.responseJSON);
}
});
}
What can I try next to fix this?