Multiple submit buttons on the form

Hey, I am very new to web programming. I have been learning PHP in the last few days, and I'm stuck in one.

I have a form tag in my code that has two submit buttons for managing data. Since I can only have one action definition in a form tag, it can lead me to only one page. (Not very sure)

Now, depending on the button pressed on the form, I want to load another page. One way is to check the button pressed in the if-else construct, and then use echo '...' in the branches and show as if it is another page. But for some reason this seems wrong. Can someone give me a better solution? Thank.

+3
source share
4 answers

One way is to use Javascript to switch the action of the form depending on which control was clicked. The following example uses the jQuery library:

<form id="theForm" action="foo.php">
...
    <input id="first" type="submit"/>
    <input id="second" type="submit"/>
</form>โ€‹

$(document).ready(function() {
    $("#theForm input").click(function(e) {
        e.preventDefault();
        if(e.target.id == 'first') {
            $("#theForm").attr("action", "somePage.php");
        } else {
            $("#theForm").attr("action", "anotherPage.php");
        }
        alert($("#theForm").attr("action"));
        $("#theForm").submit(); 
    });
โ€‹});โ€‹

Demo here: http://jsfiddle.net/CMEqC/2/

+2
source

But for some reason this seems wrong.

This is a wrong assumption.
Any other solution would be much worse.

Server-side validation is the only reliable solution.
However echo, the branches are not required. There are many other ways.
Using an operator includeis the most obvious.

+1
source

add another solution based on @ karim79, as it is marked with PHP:

<form id="theForm" action="foo.php">
...
    <input id="first" name="button" value="first" type="submit"/>
    <input id="second" name="button" value="second" type="submit"/>
</form>โ€‹

in your foo.php, do something like this:

<?php
$submit = isset($_GET['button']) ? trim($_GET['button']) : '';

if($submit == 'first')
{
   header('Location: somePage.php');
}
else if($submit == 'second')
{
   header('Location: anotherPage.php');
}
?>

Summary: in order to read on your button (2 submit buttons), you need to add namefor each of them. To make it simple, just use the same name for both. Then add different ones value. Then you need to find out which button is pressed, checking what value is sent on that particular button .

-2
source

Source: https://habr.com/ru/post/1760965/


All Articles