Multiple forms or multiple posts per page?

I am creating a page with products sold on a website. I would like to add an โ€œadd to cart" button next to each product that is listed with markup like this:

<h4 class="productHeading">Product Name 1</h4> <div> Extra information on the product 1. </div> <h4 class="productHeading">Product Name 2</h4> <div> Extra information on the product 2. </div> ... 

Since the input for sending will have different names (with the product code included), the big question is: should I wrap the entire list of products in the form or create one form for each product? In code:

 <form method="post" action="process.php"> <h4 class="productHeading">Product Name 1</h4> <div> Extra information on the product 1. <input type="submit" name="submit1" value="Add to Cart"> </div> <h4 class="productHeading">Product Name 2</h4> <div> Extra information on the product 2. <input type="submit" name="submit2" value="Add to Cart"> </div> </form> 

Or...

 <h4 class="productHeading">Product Name 1</h4> <div> Extra information on the product 1. <form method="post" action="process.php"> <input type="submit" name="submit1" value="Add to Cart"> </form> </div> <h4 class="productHeading">Product Name 2</h4> <div> Extra information on the product 2. <form method="post" action="process.php"> <input type="submit" name="submit2" value="Add to Cart"> </form> </div> 

Which one is best practice? Any serious reason not to use one or the other, or am I doing this completely wrong?

+47
html submit forms
Jan 03 2018-12-12T00:
source share
1 answer

Best practice: one form for each product is definitely the way to go.

Benefits:

  • This eliminates the need to analyze the data to find out which product was clicked.
  • This will reduce the size of the data sent.



In your specific situation

If you only ever intend to have one form element, in this case the submit button, one form should work fine for everyone.




My recommendation: Make one form per product and change the markup to something like:

 <form method="post" action=""> <input type="hidden" name="product_id" value="123"> <button type="submit" name="action" value="add_to_cart">Add to Cart</button> </form> 

This will give you a much cleaner and more convenient POST . No parsing. And this will allow you to add additional parameters in the future (size, color, quantity, etc.).

Note. There is no technical benefit to using <button> vs. <input> , but as a programmer, I find it action=='add_to_cart' to work with action=='add_to_cart' than action=='Add to Cart' . In addition, I hate mixing presentation with logic. If one day you decide that it makes sense for the button to say โ€œAddโ€ or if you want to use different languages, you can do it freely without worrying about your internal code.

+78
Jan 03 '12 at 13:13
source share
โ€” -



All Articles