Search code examples
phphtmlphp-5.3shopping-cart

How to deal with two submit buttons in a form?


I don't understand this,

if I do this and I click the check out button, the page won't go to the check out page,

<form action="cart.php" method="post" id="form-cart">
<button name="update" id="update" type="submit" value="Update cart">Update cart</button>
<button name="checkout" id="checkout" type="submit" value="Check out">Check out</button>
</form>

It only does if I change the name="checkout" to name="cart-checkout",

<form action="cart.php" method="post" id="form-cart">
<button name="update" id="update" type="submit" value="Update cart">Update cart</button>
<button name="cart-checkout" id="checkout" type="submit" value="Check out">Check out</button>
</form>

It works that way but does not make any sense to me, do you know why it does it that way?

So I tried to use <a> tag inside the <button> tag and it goes to the check out page,

<form action="cart.php" method="post" id="form-cart">
<button name="update" id="update" type="submit" value="Update cart">Update cart</button>
<button name="checkout" id="checkout" type="submit" value="Check out"><a href="checkout.php">Check out</a></button>
</form>

But does it a valid html to put <a> tag inside the <button> tag?


Solution

  • Why not change the buttons to:

    <input name="update" id="update" type="submit" value="Update cart">
    <input name="cart-checkout" id="checkout" type="submit" value="Check out">
    

    Then in PHP (on cart.php) you can do:

    <?php
      if($_POST){
         if(isset($_POST['update']){
           // process update
         } else if(isset($_POST['cart-checkout']){
           // process cart checkout
           // or uncomment the below line to forward to checkout.php
           // header("Location: checkout.php");
         }
      }
    ?>