Multiple submit buttons php different actions - php

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?

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>

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.

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

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!

Related

My HTML form has its action linked to php code. When the submit button is clicked though, the form redirects to the PHP file. How can I prevent this?

I have a signup form in my HTML file. The action of the form is a PHP file. I want the PHP to process the entered data and leave the user on the signup page (HTML.) However, when the submit button is clicked, the website redirects to the PHP file. Is there some way of preventing this?
I have tried setting the form's target to "_self", but that didn't help.
HTML:
<? include('signup.php'); ?>
<?php include('errors.php'); ?>
<form method="post" action="signup.php">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>
you can actually leave that empty, so the same page gets targeted :)
Remove or blank the action attribute in form like as:
HTML:
<?php include('signup.php');
include('errors.php');
?>
<form method="post">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>
</form>
If you don't want to refresh the page and handle user input you can use AJAX
Simple example:
<form>
<label for="username">
Username
<input type="text" id="username">
</label>
<label for="password">
Password
<input type="password" id="password">
</label>
<button id="submit"></button>
</form>
<script>
$(function () {
$('#submit').click(function () {
$.ajax({
method: 'POST',
url: 'signup.php',
data:
{
name: $('#username').val(),
password: $('#password').val()
}
}).done(function (msg) {
alert('Data Saved: ' + msg);
});
});
});
</script>
If you want to send POST request to the same page, just remove action attribute from the form
<form method="post">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>

Multiple different forms in one ajax php page

Due to language limitations I might not understood how to ask Google about what I want to accomplish, but I hope you will understand.
I have three forms which i want to show on the same page without refresh. First form submits action to php which determines which function (with yet another form) to show. But buttons interfere and I am nowhere near what I wanted to do.
Index.php is supposed to send user input to calculator.php which then opens next form depending on value:
<form id="form1" method="post" formaction="calculator.php">
<input id="form1" type="submit" value="Submit" />
<div id="parseSecondForm"></div>
<script type="text/javascript">
$(function(){
$('#form1').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('formaction'),
data: $(this).serialize(),
beforeSend: function(){
$('#parseSecondForm').html('<img src="loading.gif" />');
},
success: function(data){
$('#parseSecondForm').html(data);
}
});
});
});
</script>
calculator.php receives user input and echoes next form in #parseSecondForm div in index.php:
if (form1 === '1') {
echo '
<form id="form2" method="post" formaction="form2.php">
<input id="form2" type="submit" value="Submit" />
<div id="thankyou"></div>
<!--submit saves php result in MySQL and thanks the user in next div-->
';
}
else {
echo '
<form id="form3" method="post" formaction="form3.php">
<input id="form3" type="submit" value="Submit" />
<div id="thankyou"></div>
<!--submit saves php result in MySQL and thanks the user in next div-->
';
}
I tried to echo modified javascript from index.php, but it just resets all the forms.
Maybe there are some form scripts designated for the cause or any other ideas how can I fix the issue?
In Javascript/HTML you cannot have two items with the same IDs:
<form id="form1" method="post" formaction="calculator.php">
<input id="form1" type="submit" value="Submit" />
form1 can be used only once.
Same for the php dynamically created forms.

how does method POST processes/excecutes in PHP

I am building a web application, I am having lots of confusion when ever I use POST method.
Lets say I have the below code
<?php
$abc = 'abc';
if(some condition){
$abc = 'xyz';
}
if(isset($_POST['submit'])){
header("Location:http://someexample.php/$abc");
die();
}
?>
<form method="POST">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
so as per my understanding, If I am not wrong.
When I click the SUBMIT / CLEAR button. The PHP file reloads the self page first before redirecting it to the header location.
If I am right. Is there any other way to avoid multiple redirects when we are working on big PHP files. When I have multiple SUBMIT button.
thank you in advance
You are basically redirecting your request to another page. Instead of redirecting the page using header you should use the action attribute of the form.
<form method="POST" action="yourexample.php" id="myForm">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
the form will redirect you to the second page. If you do not want to reload your page at all you should use ajax. You can use jquery and post your values to another page buy creating a function. In this case your form tag should not have the action attribute or you
should use preventDefault method.
$("#myForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
url will be the name of the page to which you want to redirect the user.
The data will be your form. You can use the .serialize() method to get your form data.
var data = $("myForm").serialize();
In success you can define a function on what to do in case of successful result.
Nothing wrong with multiple redirects: this is how traditional web works.
You may get reduce the number of redirects by using AJAX calls though.
Some notes on your pseudo-code:
it is quite useless to echo anything before Location header: noone is supposed to read the message. Not to mention that no output is allowed before headers.
http:// in front of address allowed only in case of fully qualified URI.
so, the code actually have to be
<?php
if(isset($_POST['submit'])){
header("Location: someexample.php");
die();
}
?>
Forms always post to the "action" attribute in it. If you don't want it to post to self, put your form opening tag as <form action="someexample.php" method="post">. The result will be the POST data being sent to someexample.php instead of to the same page as the form.
If you're looking into multiple form options on one page without redirect, take a look into AJAX submits.
The idea would be to send over the form to your receiving file, process the POST data, and return whatever you wanted returned from that process. For example:
$("form").submit( function(event) {
event.preventDefault(); //prevent the file submitting
var formData = $(this).serialize(); //process the form into an array for submission
$.ajax({
url: "receiver.php", //the url of the receiving file
type: "post", //setting method to post
data: formData, //set the data being sent to the form contents
success: function(response) {
$("div").html(response); //set the receiving div to the html you echo'd in the php document
}
});
});
Your receiver.php file can look exactly the same as a normal PHP document receiving POST data, so <?php if(isset($_POST['submit'])) {} ?> will still work exactly as you're expecting, without the page redirects! This solution does require jQuery though.
Edit:
To deal with the questions update of if(criteria) { $abc = 'xyz'; } there are a couple of suggestions.
To keep the asynchronous approach, go with $_SESSION variables. You could set them using the receiver.php and deal with them in the starting document.
To go back to a standard submission method onto the same document, either break your multiple options into radio inputs, checkboxes, or separate forms.
So:
<input type="radio" name="method" value="submit" />
<input type="radio" name="method" value="clear" />
That way you can choose what method to submit there.
Or you can break them into forms:
<form method="post">
<input type="submit" name="submit" value="submit" />
</form>
<form method="post">
<input type="submit" name="clear" value="clear" />
</form>
Finally, you could change the value of a hidden input on click if you wanted to change between submit and clear, so:
The HTML:
<form method="post">
<input type="hidden" id="method" name="method" value="" />
<input type="submit" id="submit" value="submit" name="submit" />
<input type="submit" id="clear" value="clear" name="clear" />
</form>
The jQuery:
$("#submit").click( function(event) {
event.preventDefault();
$("#method").val("clear"); //set the method to clear
$("form").submit(); //submit the form normally
});
$("#clear").click( function(event) {
event.preventDefault();
$("#method").val("submit");
$("form").submit();
});
The PHP:
<?php
if(isset($_POST['submit'])) {
//do something
} elseif(isset($_POST['clear'])) {
//do something else
}

processing a form without refreshing the page using jquery and ajax

I have a form which I want to submit without refreshing the whole page.
I've found a ready source code and implemented it on my pages, but it refuses to work!
here is the html form I need to submit:
<form method="POST" action="" name="actionForm" id="actionForm" class="actionForm">
<input type="hidden" name="adID" value="'.$row['adID'].'" />
<input type="hidden" name="adStatus" value="'.$row['adStatus'].'" />
<input type="submit" name="editAd" value="ערוך מודעה" class="actionButtons" />
<input type="submit" name="upgradeAd" value="הקפץ מודעה" class="actionButtons" />
<input type="submit" name="changeAdStatus" class="actionButtons" value="';
if ($row['adStatus'] == "disabled")
echo 'הצג מודעה בלוח" />';
else
echo 'הסתר מודעה מהלוח" />';
echo '
<input type="submit" name="deleteAd" value="מחק מודעה" class="deleteButton" />
</form>
and here is the script to forward to the processing php file and writing some results on the current page:
<script>
$(document).ready(function(){
$("#actionForm").validate({
debug: false,
rules: {
submitHandler: function(form) {
$.post('/tests/process.php', $("#actionForm").serialize(), function(data) {
$('#resDiv').html(data);
});
}
}});
});
</script>
the processing php only writes data to the database and prints a confirm message.
here is the link to it: http://codeviewer.org/view/code:29c4
I've inspected every single line of the code but still can't get why I see no message from the processing php...
any ideas?
thanks in advance for your help!
P.S. here is the full code of the initial php: http://codeviewer.org/view/code:29c3
I think your javascript snippet at the end of your code is wrong. The submit handler must not be in the rules: {} block.
Try the following:
<script>
$(document).ready(function() {
$("#actionForm").validate({
debug: false,
submitHandler: function(form) {
$.post('/tests/process.php', $("#actionForm").serialize(), function(data) {
$('#resDiv').html(data);
});
}
});
});
</script>

Ajax with multiple submit buttons

How can I change the code below so instead of a text input type with a submit button I want multiple submit buttons each with their own unique value? Everything I try just ends up with submit's value being undefined. Any help would be great!
Code source: Submit Search query & get Search result without refresh
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" name="send" id="send">
</form>
You can add multiple submit buttons and attach to all of them onclick event listener. When button was clicked - get the value and send with a POST request.
<script>
$(function(){
$('input[type=submit]').click(function(){
$.post('db_query.php', {value:$(this).val()}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="">
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
</form>
If you want to use multiple submit buttons, you can catch the click event and determine which button was clicked. then run different Ajax submit. this also works when enter is hit.
//submit buttons
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str" />
<input type="submit" value="v1"/>
<input type="submit" value="v2"/>
//...more submit buttons
</form>
//submit func
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val){
case 'v1':...;
case 'v2':...
}
});
});
Here is my version - which now looks very much like Bingjies because it was written while I was testing out his version
DEMO
<form id="lets_search" action="" >
Search:<input type="text" name="q" id="q">
<input type="submit" value="Google" name="send" id="google">
<input type="submit" value="Bing" name="send" id="bing">
</form>
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val()) {
case "Bing" :
$("#lets_search").attr("action","http://www.bing.com/search");
break;
case "Google":
$("#lets_search").attr("action","https://www.google.com/search");
break;
}
});
});
Here, I would prefer to Vamsi's solution n Why not Sanjeev mk?
Give some extra thought on prefering the solution.
case: If there are mulitple submit buttons
If the user is in the text field and hits enter, the system will assume the first submit button was hit.
So, here, it would be good to go for not having mulitple submit
buttons for end user point of view
You can have multiple submit buttons in the form, no problem. They may have the same name, type etc, but just assign them different values. Like Submit Button 1 can have value="hi" and Button 2 can have value="bye".
Then when the action function is called for the button, all you have to do when entering the function is do a check with: $(this).val
HTML:
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
jQuery:
$(function() {
$("#lets_search").bind('submit',function() {
var value = $(this).val();
if(value == "hi")
do_something;
else
do_something_else;
});
});

Categories