1

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?

1
  • If an AJAX call fails, you may be able to see what is going wrong in your browser's Network tab. What does it say? Commented Oct 13, 2024 at 16:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.