Multiple submit buttons php different actions
Asked Answered
S

4

31

I have a website started where I want to have 2 separate submit buttons, one of which will take data entered and do some calculations to it to display on the same screen. I've got this successfully working with:

<form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
<input type="submit" name="calc" value="Find Angle">

and then I use:

if (!isset($_POST['submit'])){
Do actions, display calculations}

Now I want a second submit button that still grabs the data they entered but then goes to a different address. Is there an elegant way to do this?

Sputter answered 21/5, 2012 at 19:50 Comment(0)
Q
49

You could add an onclick method to the new submit button that will change the action of the form and then submit it.

<script type="text/javascript">
  function submitForm(action) {
    var form = document.getElementById('form1');
    form.action = action;
    form.submit();
  }
</script>

...

<form id="form1">
  <!-- ... -->
  <input type="button" onclick="submitForm('page1.php')" value="submit 1" />
  <input type="button" onclick="submitForm('page2.php')" value="submit 2" />
</form>
Qumran answered 21/5, 2012 at 19:52 Comment(8)
It works! Thanks a lot! I spent an hour looking at slightly different cases than mine and couldn't figure it out. You got it in 3 seconds :-) I have so much more to learn..Sputter
What if the user just hits the Enter key without clicking on any submit button?Impediment
@IstiaqueAhmed: Unless you change it, it will submit the form with whatever action it has by default. If that's not what you want, you can set up whatever behavior you want via an onsubmit listener on the <form> element.Qumran
By-default submission will get the first button, so if the user intends to use the second button, then that is not possible. How to solve this situation with onsubmit ?Impediment
@IstiaqueAhmed: It sounds like you're using <input type="submit">. This answer is using <input type="button">. There's a difference. With regular buttons in the form, no button is used when the user hits Enter.Qumran
Great answer. Oddly, I couldn't get the form element to be recognized by the function until I specified that the <script> was <script type="text/javascript">.Nan
@frozenjim: I should have included type="text/javascript" in my answer. In HTML5, type="text/javascript" is the default, so you can leave it off. But this requires that you use <!DOCTYPE html>. If you're not using HTML5 (or greater, in the future), then you must specify the script type.Qumran
@Qumran Thanks so much for that. Simple solution for a potential problem.Koniology
J
20

You can change the form action by using formaction="page1.php" in button property .

<form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
    <input type="submit" name="calc" value="Find Angle">

    <input type="button" type="submit" formaction="page1.php">Action 0</button>
    <input type="button" type="submit" formaction="page2.php">Action 1</button>
</form>

Note: The formaction attribute of the button tag is not supported in Internet Explorer 9 and earlier versions.

Jankowski answered 28/7, 2014 at 6:55 Comment(1)
Indeed, there is such attribute as formaction in HTML5 standard.Gibby
S
13

The best way to deal with multiple submit button is using switch case in action script

<form action="demo_form.php" method="get">

    Choose your favorite subject:

    <button name="subject" type="submit" value="html">HTML</button>
    <button name="subject" type="submit" value="css">CSS</button>
    <button name="subject" type="submit" value="javascript">Java Script</button>
    <button name="subject" type="submit" value="jquery">jQuery</button>

</form>

Action / Server Side script:

demo_form.php

<?php

switch($_REQUEST['subject']) {

    case 'html': //action for html here
                break;

    case 'css': //action for css here
                break;

    case 'javascript': //action for javascript here
                        break;

    case 'jquery': //action for jquery here
                    break;
}

?>

Ref: W3Schools

Sonde answered 5/8, 2016 at 5:23 Comment(1)
I know this question/answer is a bit old but just a note: this solution doesn't go to a different address as requested.Peruke
S
0

Another approach is that You can create and Use some session variable to achieve it easily.

E.g. $_SESSION['validate'].

HTML and PHP Code for buttons

<button type="submit" id="first_submit" style="<?php echo isset($_SESSION['validate'])?'display:none':'';?>">first submit</button>
<button type="submit" id="second_submit" style="<?php echo isset($_SESSION['validate'])?'':'display:none';?>">second submit</button>

jquery and ajax Script

<script>
    $(document).ready(function(){

        $("#form").on('submit', function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'handler-file.php',
                data:  new FormData(this),
                dataType: "json",
                enctype: 'multipart/form-data',
                contentType: false,
                cache: false,
                processData:false,
                error:function(error){
                    //your required code or alert
                    alert(error.responseText);
                },
                success: function(response){
                    if(response.status=='1')
                    {
                        //your required code or alert
                        $('#first_submit').hide();
                        $('#second_submit').show();
                    }
                    else if(response.status=='2')
                    {
                        //your required code or alert
                        $('#first_submit').show();
                        $('#second_submit').hide();
                    }
                    else
                    {
                        //your required code or alert
                    }
                }
            });
        });

    });
    </script>

Handler PHP File

<?php
session_start();

$result['status']='0';
$result['error']='';

if(!isset($_SESSION['validate']))
{
    if(!isset($_FILES['file'])) 
    {
        $result['error'].='[Er-02 file missing!]';
    }
    else
    {
        //your other code
        $_SESSION['validate'] = true;
        $result['status']='1';
    }
}
else if($_SESSION['validate']==true)
{
    if(!isset($_FILES['file'])) 
    {
        $result['error'].='[Er-03 Validation file missing!]';
    }
    else
    {
        //your other code
        unset($_SESSION['validate']);
        $result['status']='2';
    }
}
else
{
    $result['error'].='[Er-01 Invalid source!]';
}
echo json_encode($result); 

?>

It may not be the optimal or efficient solution. My level of experience is not too much, so I came up with this solution what served my purpose best after all the solutions available but with their limitations. This was not anywhere so thought to write it here.

Note: You may notice it includes some other parts like response, success and error handling between presentation, script and backend file.

Hope it helps!

Sell answered 3/6, 2020 at 7:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.