How to Create Two Submit Buttons with Different Action in One Form

Getting Started

To slightly beautify our app, I've use Bootstrap which is included in the downloadable of this tutorial but if you want, you can download it yourself using this link. In this tutorial, I'm not gonna use any database but I'm going to use PHP SESSION to hold data.

Creating our Form and Script

Finally, we create our form which contains two submit buttons and the javascript that assign different actions to the two buttons. Create a new file, name it as index.php and paste the codes below.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>How to Create Two Submit Buttons with Different Action in One Form</title>
  6. <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10. <h1 class="page-header text-center">Two Submit Buttons with Different Action</h1>
  11. <div class="row">
  12. <div class="col-sm-3 col-sm-offset-2">
  13. <h3>Submit Form</h3>
  14. <form method="POST" id="myForm">
  15. <div class="form-group">
  16. <label for="firstname">Firstname</label>
  17. <input type="text" class="form-control" id="firstname" name="firstname">
  18. </div>
  19. <button type="submit" class="btn btn-primary" onclick="submitForm('page1.php')">Submit1</button>
  20. <button type="submit" class="btn btn-primary" onclick="submitForm('page2.php')">Submit2</button>
  21. </form>
  22. </div>
  23. <div class="col-sm-5">
  24. <table class="table table-bordered">
  25. <thead>
  26. <th>Firstname</th>
  27. <th>Submitted Via</th>
  28. </thead>
  29. <tbody>
  30. <?php
  31.  
  32. if(!isset($_SESSION['names'])){
  33. $_SESSION['names'] = array();
  34. }
  35.  
  36. foreach($_SESSION['names'] as $row){
  37. echo "
  38. <tr>
  39. <td>".$row['firstname']."</td>
  40. <td>".$row['sub_via']."</td>
  41. </tr>
  42. ";
  43. }
  44. ?>
  45. </tbody>
  46. </table>
  47. </div>
  48. </div>
  49. </div>
  50.  
  51. <script type="text/javascript">
  52. function submitForm(action) {
  53. var form = document.getElementById('myForm');
  54. form.action = action;
  55. form.submit();
  56. }
  57. </script>
  58. </body>
  59. </html>

Creating our Actions

Lastly, we create the two actions for our two submit buttons. Create the ff files and paste the codes below them. page1.php
  1. <?php
  2.  
  3. $data['firstname'] = $_POST['firstname'];
  4. $data['sub_via'] = 'Submit1';
  5.  
  6. array_push($_SESSION['names'], $data);
  7.  
  8. header('location: index.php');
  9. ?>
page2.php
  1. <?php
  2.  
  3. $data['firstname'] = $_POST['firstname'];
  4. $data['sub_via'] = 'Submit2';
  5.  
  6. array_push($_SESSION['names'], $data);
  7.  
  8. header('location: index.php');
  9. ?>
That ends this tutorial. Happy Coding :)

Add new comment