How can I determine which button was pressed in a PHP form?

I have several buttons on my page, but I'm not sure how to determine which one was clicked. Here's the markup for my two buttons:

<input type="submit" id="btnSubmit" value="Save Changes" /> <input type="submit" id="btnDelete" value="Delete" /> 
+73
php
Apr 21 '10 at 3:44
source share
3 answers

With an HTML form such as:

 <input type="submit" name="btnSubmit" value="Save Changes" /> <input type="submit" name="btnDelete" value="Delete" /> 

The PHP code to use will look like this:

 if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Something posted if (isset($_POST['btnDelete'])) { // btnDelete } else { // Assume btnSubmit } } 

You should always assume or use the default first submit button to display as HTML source code . In practice, various browsers reliably send the name / value of the submit button with the publication data when:

  1. User literally presses send button with mouse or pointing device
  2. Or there is focus on the submit button (they are embedded in it), and then the Enter key is pressed.

There are other ways to submit the form, and some browsers / versions decide not to submit the name / value of any submit buttons in some of these situations. For example, many users submit forms by pressing the Enter key when the cursor / focus is on the text field. Forms can also be submitted via JavaScript, as well as some more obscure methods.

It is important to pay attention to this detail, otherwise you can really upset your users when they submit the form, but β€œnothing happens” and their data is lost because your code could not detect the form being submitted because you did not foresee the fact that the name / the submit button value cannot be sent with publication data.

In addition, the above advice should be used for forms with one submit button, since you should always use the default submit button.

I know that the Internet is filled with tons of tutorials on form handlers, and almost all of them do just checking the name and value of the submit button. But they are just wrong!

+135
Apr 21 '10 at 3:53 on
source share

In HTML:

 <input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" /> <input type="submit" id="btnDelete" name="btnDelete" value="Delete" /> 

In PHP:

 if (isset($_POST["btnSubmit"])){ // "Save Changes" clicked } else if (isset($_POST["btnDelete"])){ // "Delete" clicked } 
+10
Apr 21 '10 at 3:51
source share

Are you asking in php or javascript.

If it is in php, specify its name and use the post or get method, after that you can use the isset option or this particular button name is checked for this value.

If it is in js, use getElementById for this

-2
Apr 21 '10 at 3:52
source share



All Articles