tags:

views:

1320

answers:

6

I have two submit buttons in a form. How do I determine which one was hit serverside?

+9  A: 

If you give each one a name, the clicked one will be sent through as any other input.

<input type="submit" name="button_1" value="Click me">
Greg
A: 

I think you should be able to read the name/value in your GET array. I think that the button that wasn't clicked wont appear in that list.

SkippyFire
You most probably mean the POST array.
ypnos
Either or right?
SkippyFire
Not necessarily, if the form's method is "POST" it won't show up in the GET array. Most forms are submitted via POST.
Parrots
Either/or is technically right, and yet so wrong. You can submit a form with method="GET", but it is cringeworthy.
Bill the Lizard
It is only "cringeworthy" when used inappropriately: http://www.w3.org/2001/tag/doc/whenToUseGet.html.
mercator
Yeah I wasn't trying to suggest GET, I was just trying to generalize things.
SkippyFire
A: 

Make sure each has an id= attribute. The one used should have a value assigned. Just check and make sure it isn't null and it was the one selected.

Zachery Delafosse
A: 

This is extremely easy to test

<form action="" method="get">

<input type="submit" name="sb" value="One">
<input type="submit" name="sb" value="Two">
<input type="submit" name="sb" value="Three">

</form>

Just put that in an HTML page, click the buttons, and look at the URL

Peter Bailey
A: 

RoBorg is right, but be careful of something - at least IE6 and Firefox3 behave differently when you hit "Enter" to submit instead of clicking a submit button. FF3 seems to send the name/value pair of the first submit input along with the rest of the form, while IE6 doesn't send any of the submit inputs.

Pavel Lishin
+5  A: 

You can give each input a different value and keep the same name:

<input type="submit" name="action" value="Update" />
<input type="submit" name="action" value="Delete" />

Then in the code check to see which was triggered:

if ($_POST['action'] == 'Update') {
    //action for update here
} else if ($_POST['action'] == 'Delete') {
    //action for delete
} else {
    //invalid action!
}

The only problem with that is you tie your logic to the text within the input. You could also give each one a unique name and just check the $_POST for the existence of that input:

<input type="submit" name="update_button" value="Update" />
<input type="submit" name="delete_button" value="Delete" />

And in the code:

if (isset($_POST['update_button')) {
    //update action
} else if (isset($_POST['delete_button'])) {
    //delete action
} else {
    //no button pressed
}
Parrots