0

I have a simple html form:

<form action="addToCart" method="post"><br><br> 

    <input name="productId"
value="${product.id}" type="hidden"> <input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>"
type="submit"> 


</form>

Every time I click on "submit", it brings me straight back to top which creates a poor user experience because the user would have to scroll back down where he was browsing the products... Can I do this without using a script?

user23524697
  • 137
  • 1
  • 6
  • 18

3 Answers3

1

Ajax is your best bet if you want to achieve what you want

 $('.submit').on('click',function(event){
     event.preventDefault(); //this is important else page will get submitted
     $.ajax({
      url:'where you want to process data',
      dataType:'html',
      data: your form data as json or whatever type
      success: function(result){
      //here you can update any thing on the frontside
      }
     });
    });
Abhinav
  • 8,028
  • 12
  • 48
  • 89
1

-Every time I click on "submit", it brings me straight back to top.

Yes that is what default functionality when submitting forms, it always repaints the dom so it causes a jump and page's top position is rendered.

-which creates a poor user experience because the user would have to scroll back down where he was browsing the products

To make a good user experience you can use ajax for this functionality, as you tagged jQuery in your question then you can try with jquery ajax:

$('form').submit(function(e){
    e.preventDefault(); // stops the form submission

    $.ajax({
      url:$(this).attr('action'), // action attribute of form to send the values
      type:$(this).attr('method'), // method used in the form
      data:$(this).serialize(), // data to be sent to php
      dataType:"text",
      success:function(data){
          alert(data); // you can alert the success message.
      },
      error:function(err){
          console.log(err);
      }
    });

});

I have used a dataType:"text", just assuming if you are going to echo "Added in the cart."; kind of message from the php.

Jai
  • 74,255
  • 12
  • 74
  • 103
0

Since you're using onclick attribute on your button, you have to change type attribute from submit to button. That way you can get your addedCart() method to fire. Then handle form submission inside that method (if your submit handler isn't already there).

<input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>" type="button">

Script:

function addedCart(){
    // ... your method on click
    // $.ajax({...});
}; 

If you're not using jQuery, you can handle form submission with XMLHttpRequest :
How to make an AJAX call without jQuery?

Community
  • 1
  • 1
Artur Filipiak
  • 9,027
  • 4
  • 30
  • 56