0

I have the following setup: https://jsfiddle.net/uosLke60/

input.Add_To_Cart_Button {
  background-color: #000;
  color: #fff;
  border: none;
  font: inherit;
  cursor: pointer;
  font-size: 13px;
  margin-bottom: 40px;
  width: 120px;
  -webkit-appearance: none;
  border-radius: 0;
}
<div class="Product_Card_Button">
  <form method="post" action="/cart/add">
    <quantity-input class="quantity" style="width: 120px; min-height: 25.4px; display: inline-flex;">
      <button class="quantity__button no-js-hidden" name="minus" type="button"> - </button>
      <input class="quantity__input" type="number" name="quantity" id="quantity" min="1" value="1" style="text-align: center;">
      <button class="quantity__button no-js-hidden" name="plus" type="button">+</button>
    </quantity-input>
    <br>
    <input type="submit" value="Add to cart" class="Add_To_Cart_Button" />
  </form>
</div>

When the add to cart button is pressed, the page refreshes. How can I adjust it so that the product is added to cart without the page refresh? I have tried a number of jQuery solutions suggested in other posts but without any luck. Any suggestions would be helpful. Thanks.

fiddle
  • 25
  • 8
  • Welcome to Stack Overflow. To address this question, you will need to learn to make use of AJAX. I would advise looking at some AJAX Tutorials. You can then use `$.post()` or `$.ajax()` to send the form data to your cart handler via AJAX without refreshing the page. – Twisty Jun 03 '22 at 17:14
  • Research AJAX, then incorporate that in to @Sampgun's answer. – Rory McCrossan Jun 03 '22 at 18:04
  • Does this answer your question? [Submit form without page reloading](https://stackoverflow.com/questions/2866063/submit-form-without-page-reloading) – isherwood Jun 03 '22 at 20:32

1 Answers1

0

You should listen for the submit event on your form and:

  1. call event.preventDefault() which blocks the default action (in your case the form submit)
  2. return false, which ultimately cancels the event

I would do something like this


    function handleAddToCart(form) {
        const url = form.getAttribute("action");
      const formData = new FormData(form);
      doSomePost(url, formData);
    }
    
    // Cache this if possible
    document.querySelector("[add-to-cart-form]")
    .addEventListener("submit", (e) => {
        e.preventDefault();
      handleAddToCart(e.target);  
      return false;
    });

I updated your fiddle as well => fiddle

Sampgun
  • 2,822
  • 1
  • 21
  • 38