Stay on the same page after adding a product to cart

cecibowles
New Member
1 0 0

I am attempting to provide an add to cart feature on a wholesale product list page for every single product. The issue is that every time the product is added to cart it redirects to the cart page. I believe it is something in the javascript since the add to cart feature is set up as a button and is functioning to submit forms. Is there a method to add it? I have tried adding a "event.preventDefault()" but it prevents the action of add to cart from working. Also attempted a "return false;" but again no luck! Let me know if I'm missing something?

 

<td colspan="8" class="text-right">
      <button type="button" id="add-to-cart-wholesale-btn" class="Button Button--primary btn add-to-cart-wholesale">Add to cart</button>
    </td>
// Wholesale add to cart function
document.getElementById("add-to-cart-wholesale-btn").addEventListener("click", function() {
  var formData = {
    items: []
  }
  $('.cart-rows').each(function() {
    if ($(this).val() == 0 || $(this).val() == undefined) {
    } else {
      formData.items.push({
        'id': $(this).data('id'),  
        'quantity': $(this).val(),
      })
    }
  });



  console.log('cart event is firing', formData);
  fetch('/cart/add.js', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(formData)
  })
  .then(response => {
    window.location.href = "/cart";
    return response.json();
    console.log(response.json());
  })
  .catch((error) => {
    console.error('Error:', error);
  });
});

Screen Shot 2021-09-17 at 1.53.50 PM.pngScreen Shot 2021-09-17 at 1.54.25 PM.pngScreen Shot 2021-09-17 at 1.55.09 PM.png 

0 Likes