Home > Backend Development > PHP Tutorial > How do you Identify Which Button Was Clicked in a PHP Form Submission?

How do you Identify Which Button Was Clicked in a PHP Form Submission?

Barbara Streisand
Release: 2024-11-11 20:28:03
Original
1011 people have browsed it

How do you Identify Which Button Was Clicked in a PHP Form Submission?

Identifying the Clicked Button in PHP Form Submissions

When working with PHP forms, identifying which button initiated the submission is crucial for handling different actions.

Determining Button Click via Form Submission Method

In a form using the POST method:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Something posted

  if (isset($_POST['btnDelete'])) {
    // btnDelete was clicked
  } else {
    // Assume btnSubmit was clicked (default)
  }
}
Copy after login

In this case, the $_POST array will contain the name of the button that was clicked. If $_POST['btnDelete'] is set, it means that the "Delete" button was clicked. Otherwise, we assume that the "Save Changes" button was clicked.

Handling Multiple Buttons

For forms with multiple submit buttons:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Something posted

  if (isset($_POST['btnSubmit1'])) {
    // btnSubmit1 was clicked
  } else if (isset($_POST['btnSubmit2'])) {
    // btnSubmit2 was clicked
  } else {
    // Assume btnSubmit3 was clicked (default)
  }
}
Copy after login

We iterate through the names of the submit buttons and check if the corresponding key exists in $_POST. Only buttons that appear later in the form HTML need to be explicitly checked. The first button should always be assumed to be the submitter unless we detect otherwise.

Additional Considerations

  • For forms using the GET method, use isset($_GET['submitted']) to detect form submission (as GET is the default request method).
  • This strategy provides excellent browser support and relies on standard HTML and PHP behavior.

The above is the detailed content of How do you Identify Which Button Was Clicked in a PHP Form Submission?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template