RGriffiths RGriffiths - 28 days ago 19
HTML Question

Identifying which button has triggered Form Post

I currently have a page that has a

form
such as this:

<form method="post">
<input name="data1" type="hidden" value="x">
<input name="data2" type="hidden" value="y">

<button name="button1" formaction="page1.php">Do something</button>
<button name="button2" formaction="page2.php">Do something else</button>

</form>


To tidy this up I would like to consolidate page1 and page2 into one but I would need to be able to identify which button fired it. So I would have something like this:

<form method="post">
<input name="data1" type="hidden" value="x">
<input name="data2" type="hidden" value="y">

<button name="button1" formaction="page.php">Do something</button>
<button name="button2" formaction="page.php">Do something else</button>
</form>


Is it possible for page.php to know which button fired it?

Answer

There's nothing to change in your <form /> here, thour PHP script will know which button has been clicked thanks to the name attribute :

<?php
if (isset($_POST['button1'])) {
    echo 'button1 has been clicked!';
} else if (isset($_POST['button2'])) {
    echo 'button2 has been clicked!';
}