Multiple form actions with two submit buttons

I’m building a shopping cart with a wish list and a cart. On the products page to go to the cart, users click on an add to cart button. I would like to add an add to wish list button. For this to work, the button will need yo send variables to the wish list page. How can I include both buttons on the same form taking them to completely different pages? I am trying to avoid a JavaScript solution.

Just make two forms.

If you insist on two buttons, without JS, then you risk some users hitting the Enter key and submitting the form with the first submit button (depending on which browser you test this on).

If you still want two submit buttons then give each of them a different name.

Test what is posted back with:


<?PHP
if( isset($_POST) )
   var_dump($_POST);

?>

<form action = "" method = "POST">
<input value="a test value" />
<input type = submit name= "buy" value = "buy" />
<input type = submit name= "add" value = "add" />
</form>


Try hitting “Enter” in various browsers, especially IE6/7/8

I’m not worried about them hitting enter. They can always take something out of the cart. Really what I was looking for was can you have more than one action in the form. That way if they hit one it will do one action, and if they hit the other, it will perform that action.

Another option:

I’m assuming users currently click check boxes for each product to select it in a form. Instead of using a form, you could dynamically list your products from the db and instead of outputting a checkbox for each product, dynamically output a “buy” or “add” button for each product. Each of the 2 buttons would be a link to the appropriate php processing script and each link would have the product’s prod_id attached in the query string.

So depending on which button was clicked for a product, the processing script would receive the prod_id for the product and then process that product accordingly in the script.

With the above you don’t need javascript at all.

You can fork your code in the form handler depending on which button was pressed.


<?PHP
if( isset($_POST) ){
   var_dump($_POST);

  if( isset($_POST['buy']){
  // ADD to your cart

  }else{
  // ADD to your list

  }
}
?>

<form action = "" method = "POST">
<!--I gave the input below a name-->
<input name="x" value="a test value" />
<input type = submit name= "buy" value = "buy" />
<input type = submit name= "add" value = "add" />
</form>

You can have 2 actions - but you will need JS to process the action.