PHP - Multiple form buttons with different actions - php

I have a simple form in HTML that contains two buttons. Button 1 which action in the form tag submits it to another php page e.g. button1-action.php which submits data to a third party API and Button 2 which I want to submit to the same page if it is clicked without going to button1-action.php.
In its simplest method the form is as follows:
<?php
echo '<form name="form123" id="form123" action="button1-action.php" method="POST">';
echo '<input type="text" name="first_name" id="first_name></input>';
echo '<button name="button1" id="button1" value="button1">Button 1</button>';
echo '<button name="button2" id="button2" value="button2">Button 2</button>';
echo '</form>';
?>
This is what I tried so far
$action = null;
if (isset($_POST['button1'])) {
$action = 'button1-action.php';
} elseif (isset($_POST['button2'])) {
$action = $_SERVER["PHP_SELF"];
}
echo '<form name="form123" id="form123" action="' . $action . '" method="POST">';
echo '<input type="text" name="first_name" id="first_name></input>';
echo '<button name=" button1" id="button1" value="button1">Button 1</button>';
echo '<button name="button2" id="button2" value="button2">Button 2</button>';
echo '</form>';
However, it doesn't seem to be working. I tried to look for solutions but I haven't been successful.
I'm interested in any solution, but I would prefer solving it using PHP and not JavaScript.

The Issue might be that you forgot to close the <form> tag with </form> and you should use the <input> for buttons aswell with type="submit" .
If this still doesn't resolve your issue then maybe you should try this :
On the same page.
<?PHP
//// place this on top
if($_POST["button1"]) {
// add code to send data to Third Party API
}
if($_POST["button2"]) {
// will show data here
} ?>
////////
<?php
echo '<form name="form123" id="form123" action="/">';
echo '<input type="text" name="first_name" id="first_name></input>';
echo '<input type="submit" name="button1" id="button1" value="button1" >';
echo '<input type="submit" name="button2" id="button2" value="button2" >';
echo '</form>';
?>
I hope this answers your question 😊

This is the solution for you in html
<form name="form123" id="form123" method = "post">
<input type="text" name="first_name" id="first_name"></input>
<button name=" button1" id="button1" value="button1" formaction="button1-action.php" >Button 1</button>
<button name="button2" id="button2" value="button2" >Button 2</button>
</form>
button 1 will submit the form to button1-action.php and button 2 will submit the form to same page.
Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formaction

You appear to be using the value submitted from the form to set the action of the form. This makes no sense - by the time you read the submitted values, the action has already happened. So your code would just set the action for next time the form is submitted. Not useful.
At the heart of this there seems to be a conceptual / design issue. A more sensible approach (but not the only one) would be to simply post the form to the same place every time, and then use if statements to decide what to do next.
e.g.
if (isset($_POST['button1'])) {
require_once "button1-action.php";
} elseif (isset($_POST['button2'])) {
//do whatever it is you want to do in ths script
}
else {
?>
<form name="form123" id="form123" method="POST">';
<input type="text" name="first_name" id="first_name></input>
<button name=" button1" id="button1" value="button1">Button 1</button>
<button name="button2" id="button2" value="button2">Button 2</button>
</form>
<?php
}
To improve a bit more on that, instead of using a bare require to include the code from another script, we could encapsulate the code from button1-action.php into a function which we can call, instead of a script with global scope. This makes the code more re-usable, maintainable, testable, less likely to cause scope conflicts, etc.
e.g.
if (isset($_POST['button1'])) {
callTheApi($_POST["first_name"]);
} elseif (isset($_POST['button2'])) {
doSomethingElse($_POST["first_name"]);
}
else {
?>
<form name="form123" id="form123" method="POST">';
<input type="text" name="first_name" id="first_name></input>
<button name=" button1" id="button1" value="button1">Button 1</button>
<button name="button2" id="button2" value="button2">Button 2</button>
</form>
<?php
}
(Even better if you then encapsulate that function in a class containing closely related functionality, but let's just get as far as a funtion for now.)
Alternatively, Virender Kumar's answer would also be reasonable - simply setting the form action of each button directly.

First of all your form is not structured properly.
index.php
<form name="form123" id="form123" action="button1-action.php">
<input type="text" name="first_name" id="first_name"></input>
<button name=" button1" id="button1" value="button1">Button 1</button>
<button name="button2" id="button2" value="button2">Button 2</button>
</form>
button1-action.php
if (isset($_GET['button1'])) {
echo 'button1 submitted'; // Send data to the third party API
} else if (isset($_GET['button2'])) {
echo 'button1 submitted'; // Submit on the same page
}

Edit: ignore my solution; Virender Kumar’s solution here is correct, elegant and doesn’t need JS.
Original answer:
The issue is not with your buttons, but with the fact that a form can only post to a single endpoint (the action attribute). You will have to handle what happens with the form data from there. If you truly want your form to be posted to a different endpoint in the client based on what button the user clicks, you can’t do it without JavaScript.
If you can live with JS, this could work:
<body>
<!-- your form here -->
<script>
const form = document.forms[0]; // assuming your form is the first form on the page, or the only one
document.querySelectorAll('button').forEach(button => {
button.addEventListener('click', event => {
if (event.target.name === 'button1') {
form.action = 'button1-action.php';
} else if (event.target.name === 'button2') {
form.action = 'other-destination';
}
});
});
</script>
</body>

Related

PHP - if(isset($_POST['button1'')){... if(isset($_POST['button2'])).. not working?

I have this code:
echo'<form method="POST" action="">';
echo'Code:<input type="text" name="name">';
echo'<input type="submit" name="save" value="Save">';
echo'</form>';
if(isset($_POST['save'])){
//something
echo'<form method="POST" action="">';
echo'Code:<input type="text" name="name">';
echo'<input type="submit" name="delh" value="Delete">';
echo'</form>';
if(isset($_POST['delh'])){
// Cant show this! :(
echo "Deleted!";
}
}
When i press "DELETE", the page reloads and the message "Deleted!" remains hidden.
This is a schedule. The idea is if someone presses the Save button but has already saved an hour it says "You have already saved an hour, do you want to cancel it?". When it clicks "Delete", the hour is deleted from the database.
In the case where the Save button is pressed, but the person has not saved an hour, the delete button is not displayed.
This line:
echo "Deleted!";
Can only be reached if both of these conditions are true:
if(isset($_POST['save'])){
//...
if(isset($_POST['delh'])){
But the form you're showing contains no element named save. The first condition is false, so the code inside that if block never runs. (It may have been true in a previous request, but not in the request you're making with this form.)
You may have meant to separate those conditions?:
if(isset($_POST['save'])){
//...
}
if(isset($_POST['delh'])){
//...
}
An alternative method would be something like this.
This makes use of the fact that you can open and close PHP tags anywhere.
<?php if (isset($_POST["delh"])) { ?>
<p>Deleted!</p>
<?php } ?>
<form method="POST" action="">
Code:<input type="text" name="name">
<?php if (isset($_POST["save"])) { ?>
<input type="submit" name="delh" value="Delete" />
<?php } elseif (isset($_POST["delh"])) { ?>
<input type="submit" name="save" value="Save" />
<?php } ?>
</form>

Why won't my return work?

I only just started learning JS like 5-10 minutes ago, I was told by someone to try and create a basic validation feature, however it doesn't seem to work as wanted. It checks if field is empty, that part works. But checking if it's got something in it and carrying on running the code doesn't.
my form:
echo '<form action="index.php?action=getHashedText" method="post" name="formHash">
<br/><textarea name="text" rows="4" cols="50" placeholder="Add your text/pharse/word which you want hashing here." autofocus></textarea><br/>
<button type="button" name="button" onclick="return validate();">Hash</button>';
function validate():
<script>
function validate() {
with (window.document.formHash) {
if (formHash.text.value === "") {
alert('Field is empty!');
return false;
} else {
return true;
}
}
}
</script>
The problem is you are using a button that is not submitting the form anyway (regardless of your js), change this dom:
<button type="button" name="button" onclick="return validate();">Hash</button>
To this: Fiddle
<input type="submit" name="button" value="Hash" onclick="return validate();" />
Or you can just add type="submit" on your <button> (HT #RocketHazmat): Fiddle
<button type="submit" name="button" onclick="return validate();">Hash</button>
Or you can just remove the type on your <button> all together as the default type is submit (HT #FabrícioMatté): Fiddle
<button name="button" onclick="return validate();">Hash</button>
Also, slightly off topic but I would get in the habit of avoiding putting javascript onclicks directly on your elements. You can create listeners instead: addEventListener

Multiple Submit buttons, how do determine which one was clicked?

I have a form with multiple submit buttons.
Each submit button is an IMG SRC trash can which denotes the delete icon for messages in a web based messaging mail inbox
what is the best way to figure out which submit button icon was clicked so that I can then write the PHP/MySQL code to DELETE the message?
if(!empty($_POST)){
// How do I figure out which submit button has been clicked to get the ID of the message to delete?
}
<form method="POST">
<input src="http://www.foo.com/img.png" id="button_1">
<input src="http://www.foo.com/img.png" id="button_2">
<input src="http://www.foo.com/img.png" id="button_3">
<input src="http://www.foo.com/img.png" id="button_4">
...
<input src="http://www.foo.com/img.png" id="button_100">
</form>
Set value for each submit button and check that in php and find which one is clicked
<form method="POST">
<img src="http://www.foo.com/img.png" id="button_1" name="submit_btn" value="1">
<img src="http://www.foo.com/img.png" id="button_2" name="submit_btn" value="2">
<img src="http://www.foo.com/img.png" id="button_3" name="submit_btn" value="3">
<img src="http://www.foo.com/img.png" id="button_4" name="submit_btn" value="4">
...
<img src="http://www.foo.com/img.png" id="button_100" name="submit_btn" value="100">
</form>
echo $_POST['submit_btn']; will give you the value of which submit button is clicked
Give each button a name=""
Then you can do something like
isset($_POST['button_name']) {
// execute code here if true
}
THE solution of this problem is to use the NAME attribute of the tag input/button.
<input type="submit" name="submitSave" value="Save"/>
<input type="submit" name="submitAddComment" value="Add comment"/>
or
<button type="submit" name="submitSave">Save</button>
<button type="submit" name="submitAddComment">Add comment</button>
I think you can also use the value attribute of button tag, this is definitively not possible with input tag.
If you need to use an ID or another variable, use name="submitDelete[888]"
Then, check it with PHP:
if( isset($_POST['submitDelete']) ) {
echo key($_POST['submitDelete']);// Displays the ID to delete, e.g. 888.
}
So many years later, I like button because it allows to display a text or an image independently of the value returned.
Here is an illustration of possibilities which fits the title of this post and more cases than the OP.
<?php
if(!empty($_POST['id'])){
echo 'button '. $_POST['id'] .' clicked';
} elseif ('create' === ($_POST['action'] ?? '')) {
echo 'create clicked'; // ?action=create
} elseif (isset($_POST['action'])) {
echo 'refresh clicked'; // ?action
} elseif (isset($_POST)) {
echo 'Default clicked'; // ?
}
?>
<form method="POST">
<!-- Original Post examples -->
<button type="submit" name="id" value="1"><img src="http://www.foo.com/img.png"></button>
<button type="submit" name="id" value="2"><img src="http://www.foo.com/img.png"></button>
...
<button type="submit" name="id" value="100"><img src="http://www.foo.com/img.png"></button>
<!-- Additional possibilities -->
<!-- ?action=create -->
<button type="submit" name="action" value="create">New element</button>
<!-- ?action -->
<button type="submit" name="action">Refresh</button>
<!-- ? -->
<button type="submit">Default</button>
</form>
you can give a name and a value to each of your buttons. It will then show up under $_POST['submit']
<img src="http://www.foo.com/img.png" id="button_4" name='submit' value='4' />
You have to pass your value to the current file by declearing name and value for each.. then you can echo in your php script in order to know which one is clicked.

How to set two buttons on one form html&php

This form should calculate numbers and save
Now there are two buttons One is call Calculator and two call Save
If I press Calculator
I get the form action is going to file name save.php And I do not want it that way
How can I set it up that button do something else
Example
Calculator = Calculator
Save = save.php
Is it possible to set it
Because it is one form
Thanks to anyone who can help
<?php
error_reporting (0);
$NUM = $_POST["NUM"];
$NUM2 = $_POST["NUM2"];
$NUM = "$NUM";
$NUM2 = "$NUM2";
$subtotal= $NUM+$NUM2;
?>
<form action="save.php" method="POST" name="Calculator">
<p>
<input name="NUM" type="text" value="<?php echo $_POST["NUM"]; ?>" />
</p>
<p>+</p>
<p>
<input name="NUM2" type="text" value="<?php echo $_POST["NUM2"]; ?>" />
</p>
<p>
<input name="subtotal" type="text" value="<?php echo "$subtotal";?>" />
</p>
<p>
<input name="submit" type="submit" value="Calculator" />
<p>
<input name="submit" type="submit" value="Save" />
</p>
</form>
You can have all the logic in a single PHP script (no need to direct to a different script depending on the button). If the logic is complicated, use include statements in order to separate the code.
Name the buttons differently:
<input name="calculator_submit" type="submit" value="Calculator" />
<input name="save_submit" type="submit" value="Save" />
Then in PHP:
if (isset($_GET['calculator_submit'])) {
// ...
} else if (isset($_GET['save_submit'])) {
// ...
} else {
// ...
}
If you really need different PHP script, then you'll have to go with Javascript (function will change the form action when a submit is clicked).
Since you are now using two submit buttons, both will submit the form and go to save.php.
Make your "calculator" button an input type=button instead of submit, and handle it via JavaScript.
Just FYI:
HTML5 allows to define a different form target URL by specifying the formaction attribut on a submit button – but browser support is lousy as of now.
Form and Buttons
<input name="submit" type="button" onclick="submitForm('Calculator')" value="Calculator" />
<input name="submit" type="button" onclick="submitForm('Save.php')" value="Save" />
Some jquery:
function submitForm(path) {
$('#Calculator').attr('action', path);
$('#Calculator').submit();
}

Save function using button in php

I have a doubt on the following code. My function is not called when the save button is clicked .
This is the following code for save function,
if(isset($_POST['Save'])) // If the submit button was clicked
{
echo "hgfd";
$post['ProductSegmentCode'] = $_POST['ProductSegmentCode'];
$post['ProductSegment'] = $_POST['ProductSegment'];
$post['ProductGroup'] = $_POST['productgroup'];
// This will make sure its displayed
if(!empty($_POST['ProductSegment'])&&!empty($_POST['ProductSegmentCode'])&&!empty($_POST['productgroup']))
{
echo "SAVE";
$news->addNews($post);
?>
<script type="text/javascript">
alert("Created Sucessfully..!!");
</script>
<?
}
else
{
?>
<script type="text/javascript">
alert("Enter Mandatory Fields");
</script>
<?
}
}
following is the button format in html,
<div style="width:70px; height:32px; float:left; margin-top:16px; margin-left:4px;">
<input name="Save" type="button" class="button" value="Save">
</div>
Your button is type="button"; to get the form to submit, it needs to be type="submit". Try updating it with this and it should work (also pending you form has action="post", or no action specified; the default is post):
<input name="Save" type="submit" class="button" value="Save" onclick="Save" />
Also, you're using onclick="Save" in your button. This indicates you have a corresponding JavaScript function named Save() - though, per your code examples you do not show one. I'm assuming that this is in error and can safely be removed (the value="Save" can also be removed as you only need to check isset($_POST['Save']) and not it's actual value). All changes in-place should give you:
<input name="Save" type="submit" class="button" />
If you do, in fact, have a JavaScript function named Save(), please post its code and I can revise.
use form for sending data and use type submit
<form action="" method="post">
<input name="Save" type="submit" class="button" value="Save">
</form>
and if you want to use this
<input name="Save" type="button" class="button" value="Save" onclick="Save()">
create Save() function in javascript and use ajax call for sending data.
It looks like you should change
<input name="Save" type="button" class="button" value="Save" onclick="Save">
to a summit button.
<input name="Save" type="submit" class="button" value="Save">

Categories