How to Create Two Submit Buttons with Different Action in One Form
Submitted by nurhodelta_17 on Tuesday, April 17, 2018 - 20:21.
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.- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>How to Create Two Submit Buttons with Different Action in One Form</title>
- <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
- </head>
- <body>
- <div class="container">
- <h1 class="page-header text-center">Two Submit Buttons with Different Action</h1>
- <div class="row">
- <div class="col-sm-3 col-sm-offset-2">
- <h3>Submit Form</h3>
- <form method="POST" id="myForm">
- <div class="form-group">
- <label for="firstname">Firstname</label>
- <input type="text" class="form-control" id="firstname" name="firstname">
- </div>
- <button type="submit" class="btn btn-primary" onclick="submitForm('page1.php')">Submit1</button>
- <button type="submit" class="btn btn-primary" onclick="submitForm('page2.php')">Submit2</button>
- </form>
- </div>
- <div class="col-sm-5">
- <table class="table table-bordered">
- <thead>
- <th>Firstname</th>
- <th>Submitted Via</th>
- </thead>
- <tbody>
- <?php
- }
- foreach($_SESSION['names'] as $row){
- echo "
- <tr>
- <td>".$row['firstname']."</td>
- <td>".$row['sub_via']."</td>
- </tr>
- ";
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- </div>
- <script type="text/javascript">
- function submitForm(action) {
- var form = document.getElementById('myForm');
- form.action = action;
- form.submit();
- }
- </script>
- </body>
- </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- <?php
- $data['firstname'] = $_POST['firstname'];
- $data['sub_via'] = 'Submit1';
- ?>
- <?php
- $data['firstname'] = $_POST['firstname'];
- $data['sub_via'] = 'Submit2';
- ?>
Add new comment
- 587 views