简体   繁体   中英

How to stay on same position after submitting an html form?

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?

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
      }
     });
    });

-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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM