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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Joegramming
  • 333
  • 1
  • 3
  • 6

4 Answers4

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>
Travesty3
  • 14,351
  • 6
  • 61
  • 98
  • 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.. – Joegramming May 21 '12 at 20:01
  • What if the user just hits the Enter key without clicking on any submit button? – Istiaque Ahmed Jan 09 '14 at 11:17
  • 1
    @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 `
    ` element.
    – Travesty3 Jan 09 '14 at 14:02
  • 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` ? – Istiaque Ahmed Jan 09 '14 at 14:45
  • 2
    @IstiaqueAhmed: It sounds like you're using ``. This answer is using ``. There's a difference. With regular buttons in the form, no button is used when the user hits Enter. – Travesty3 Jan 09 '14 at 18:37
  • Great answer. Oddly, I couldn't get the form element to be recognized by the function until I specified that the – frozenjim Dec 29 '14 at 12:43
  • @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 ` `. If you're not using HTML5 (or greater, in the future), then you must specify the script type. – Travesty3 Dec 29 '14 at 16:52
  • @Travesty3 Thanks so much for that. Simple solution for a potential problem. – BeNice Jan 25 '16 at 20:53
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.

Pradeep
  • 317
  • 4
  • 9
  • Indeed, there is such attribute as [`formaction`](http://www.w3.org/TR/html-markup/button.submit.html#button.submit.attrs.formaction) in HTML5 standard. – Jasom Dotnet Dec 19 '15 at 11:06
12

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

Shailesh Sonare
  • 2,791
  • 1
  • 18
  • 14
  • I know this question/answer is a bit old but just a note: this solution doesn't go to a different address as requested. – Ezenhis Feb 07 '18 at 14:48
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!

Azum
  • 1
  • 2