please i need your help with an issue.
I have two forms on my homepage that i'll like users to fill and submit at different times. My problem is that i'll like to have only one processing page for both of them. Normally i can do this in seperate pages. But i'll like to know if doing it on the same page is possible.
Okay.. If i submit form A, on the action page, wont there be Undefined Index for variable of form B, that has not being submitted, and ofcourse using a GET is not adviced.
Thanks for your time and patience.
It's not completely unheard of to do this. Quite often, a different parameter is passed in the form element's action attribute like /submit.php?action=register or /submit.php?action=activate.
So, you have code like this:
if ($_GET['action'] == 'register') {
// Register user
} else if($_GET['action'] == 'activate' {
// Activate user
}
However, you could also just change the value of the submit button and have the action attribute the same for both forms:
if (isset($_POST['submit'])) {
if ($_POST['submit'] == 'register') {
// Register user
} else if($_POST['submit'] == 'activate') {
// Activate user
}
}
create separate form_process script then include in form pages.
if(!empty($_POST)){
include 'form_process.php';
}
form_process.php should contain only class/function without echo or print out.
alternately you may set action url to the same page then redirect back to proper page.
<form id="add-profile-form" action="form_controller.php" method="post">
<input type="hidden" name="act" value="adding"/>
<!-- form 1. -->
</form>
<form id="edit-profile-form" action="form_controller.php">
<input type="hidden" name="act" value="editing"/>
<!-- form 2. -->
</form>
form_controller.php
if(isset($_POST['act']){
if($_POST['act'] == 'adding'){
//process form1
}else if($_POST['act'] == 'editing'){
//process form2
}
header("Location: success.php");
}
You can do it on the same page also. Just you need to make action same for both the forms.
You need to make some condition and write the individual functionality for Form A and for Form B depending on the source form.
You can check with the parameters in action like #Ami has used.
/submit.php?action=register or /submit.php?action=activate
So, you have code like this:
if ($_GET['action'] == 'register') {
// Register user
} else if($_GET['action'] == 'activate' {
// Activate user
}
However, you could also just change the value of the submit button and have the action parameter the same for both forms:
if (isset($_POST['submit'])) {
if ($_POST['submit'] == 'register') {
// Register user
} else if($_POST['submit'] == 'activate') {
// Activate user
}
}
Related
I'm working on a form that I'd like to change the form action based off of the value of an input on form submit. This needs to be accomplished using PHP.
Here's what I've tried so far:
<?php
$action = "";
$input = (isset($_POST["hp"]));
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">
<!-- form stuff here -->
<input id="hp" name="hp" type="text" class="hp"/>
<input type="submit" name="submit" id="submit" value="Submit Query" class="button" />
</form>
This doesn't work because the hp field for (isset($_POST["hp"])) doesn't have a value from the get-go, so it always goes to action1.
I've also tried:
<?php
if(isset($_POST['submit'])){
$input = ($_POST['hp']);
$action = "";
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">
That didn't work because Perch (the CMS this is being built on) throws you an error that $action isn't defined yet.
And when I tried:
<?php
$action = "";
if(isset($_POST['submit'])){
$input = ($_POST['hp']);
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
It didn't do anything at all on submit because it set the action as "".
Any suggestions?
To write in short way
$action = isset($_POST['hp'])?'action2':'action1';
That's all.
Differents possibilities:
Same action and redirect
The most easy way probably is send form to the same PHP file, and in this file, get the content of this input via POST and redirect to the correct file.
Prevent default submit and add submit event via JavaScript
The second option, may be add an event to form on submit via JavaScript, prevent default action to prevent the submit, then check value of input, set action and submit form:
<form name="contactForm" id="contactForm" method="post" action="">
...
</form>
<script>
document.querySelector('#contactForm').addEventListener('submit', function(e) {
//Prevent default submit
e.preventDefault();
//Check input value
if (...) {
this.action = "page1.php";
} else if (...) {
this.action = "page1.php";
}
//perform submit form.
this.submit();
});
</script>
Use data binding library
This is probably the best form to do it, but the most complicated to understad, this form is based of use a data binding library like Vue.js, KnockoutJS or RactiveJS to set in model object the action string depending of input value.
Then, in HTML form tag, set in action the value of model data using the binding syntax of the chosen library:
//Vue.js syntax
<form name="contactForm" id="contactForm" method="post" :action="action">
//Ractive.js syntax
<form name="contactForm" id="contactForm" method="post" action="{{action}}">
What do I recommend?
If you're novel with PHP and don't know JavaScript, the first option is probably the best for you, if you If you know JavaScript and you know how to work with events, but never used a binding library, probably the second option is more recommended for you.
If you worked with some data binding library (or framework that implements data binding like Angular), the third options is probably the best for you.
If the 2nd and 3rd versions don't work, you must be missing an input like:
<input type="submit" name="submit">
You can either add that button to the form, or you can change your code to use if isset($_POST['hp'])
<?php
$action = "";
if(isset($_POST['hp'])){
$input = ($_POST['hp']);
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
None of the answers above worked for me, so here is what I ended up going with.
Use Case:
I have a "Search" form with two fields. When a user clicks "Search",
these values should be added to the URL, so that previous searches
may be bookmarked. The search should then be performed.
When the page is first loaded or no search criteria are used, all
possible results should be shown.
Code description:
At the top of the file, check if the user submitted the form.
If so:
get the values from the fields you want and save them to local variables.
navigate to the same PHP file, this time passing the variables you are interested in
If the user did not submit the form:
check for URL parameters
If there are URL parameters present, save them to local variables,
and use these local variables to run the search
Code Snippet:
if(isset($_POST['submit'])){
if(!empty($_POST['projectNameSearch'])){
$projectNameSearch = mysqli_real_escape_string($conn, $_POST['projectNameSearch']);
}
if(!empty($_POST['projectDescriptionSearch'])){
$projectDescriptionSearch = mysqli_real_escape_string($conn, $_POST['projectDescriptionSearch']);
}
if($projectNameSearch != '' || $projectDescriptionSearch != ''){
header("Location: projects.php?projectnamesearch=$projectNameSearch&projectdescriptionsearch=$projectDescriptionSearch");
}
} else {
if(isset($_GET['projectnamesearch'])){
$projectNameSearch = mysqli_real_escape_string($conn, $_GET['projectnamesearch']);
}
if(isset($_GET['projectdescriptionsearch'])){
$projectDescriptionSearch = mysqli_real_escape_string($conn, $_GET['projectdescriptionsearch']);
}
}
While designing sign up page I wish to reload page if user has submitted anything wrong in the fill up boxes. How can I reload page after the user presses submit button with a wrong entry ? (while verifying expected content through php)
You can use header() plus some _GET variables for telling the original page there were errors.
Form submit page:
<?php
//.... lots of code validation
if ($failed) {
header('Location: http://path.com/to/your/site/original_form.php?error=1');
}
?>
Form page:
<?php
if (isset($_GET['error']) {
echo "there was an error! Please fix it!";
}
?>
Try the following -
if (validation_failed) {
header("Location: http://yourserver.com/signup.php");
} else {
header("Location: http://yourserver.com/welcome.php");
}
PHP Header function
I have a multi page form (pages separated with hidden divs)
All of it is wrapped in form tags, with a submit button. However when the user clicks the submit button at the end, it will check certain criteria on the form. If all good, it will allow the form to submit, else it will preventDefault().
However in IE8+ (maybe lower too), it simply never submits the form. I have console.log'd the JS, and it fires where it should, just IE doesn't submit the form.
I then added a $('#form').submit() call to manually submit it, which it did, but no data got sent...
Any ideas? Sorry if this is a bit vague.
Html
<form method="POST" action="/members/transfer_manager.php" name="f1" id="TM_MainForm">
** Loads of form fields & table structure **
<input type="submit" class="TM_Button" id="TM_submitTransfer" name="save" value="Transfer my account{if $isclientaresellerVAL}s{/if} »" />
</form>
JavaScript
$('#TM_submitTransfer').click(function(e)
{
console.log($.TM_submitTransferERR);
// Submit the form? Let's check first matey.
$.TM_submitTransferERR = false;
if(($('#TM_Movedate').val() == '') && (!$('#TM_MoveNow').is(':checked')))
{
$('#TM_MoveDate_ERR').html($.ObjectER + "Please choose");
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Check we have some…
// Set the # of xfers
var rsxfers = $("#TM_UsernamesSubACCTSTAGC").tagit("assignedTags");
var fsxferssplitLGNTH = rsxfers.length;
var OnlySubAccts = $('#TM_only_sub_accounts').prop("checked");
console.log($.TM_submitTransferERR);
if((OnlySubAccts == true) && (fsxferssplitLGNTH < 1))
{
alert("You have not chosen any accounts to transfer");
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Check TOS
if(!$('#TM_Tos').is(':checked'))
{
// Show error?
$('#TM_Tos').focus();
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Error, return false.
if($.TM_submitTransferERR === true)
{
console.log("Don't do it!");
console.log($.TM_submitTransferERR);
e.preventDefault();
return false;
}
console.log($.TM_submitTransferERR);
console.log("do it!");
$('#TM_MainForm').submit();
return true;
});
I’m not sure whether the problem I’m having is with JavaScript or with PHP.
My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.
My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.
What am I doing wrong?
Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.
Also I have a question about choosing answers. May I choose more than one reply as an answer?
<?php
// Set variables
$selected_radio = 'test';
session_start(); // start up your PHP session!
// The below code ensures that $dest should always have a value.
if(isset($_SESSION['dest'])){
$dest = $_SESSION['dest'];
}
// Get the user's ultimate destination
if(isset($_GET['dest'])){
$_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest'];
$dest = $_SESSION['dest']; // new code
}
else {
echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value)
}
// Show the terms and conditions page
//check for cookie
if(isset($_COOKIE['lastVisit'])){
/*
Add redirect >>>> header("Location: http://www.mywebsite.com/".$dest); <<This comment code will redirect page
*/
echo "aloha amigo the cookie is seto!";
}
else {
echo "No cookies for you";
}
//Checks to see if the form was sent
if (isset($_POST['submitit'])) {
//Checks that a radio button has been selected
if (isset($_POST['myradiobutton'])) {
$selected_radio = $_POST['myradiobutton'];
//If No has been selected the user is redirected to the front page. Add code later
if ($selected_radio == 'NO') {
echo "NO status checked";
}
//If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later
else if ($selected_radio == 'YES') {
echo "YES status checked";
// header("Location: http://www.mywebsite.com/".$dest);
}
}
}
?>
<HTML>
<HEAD>
<TITLE>User Agreement</TITLE>
<script language="javascript">
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
thisform.submit(); // this line submits the form after validation
}
</script>
</HEAD>
<BODY>
<H1> User Agreement </H1>
<P>Before downloading you must agree to be bound by the following terms and conditions;</P>
<form name="myform" METHOD ="POST" ACTION ="user_agreement4.php">
<input type="radio" value="NO" name="myradiobutton" />NO<br />
<input type="radio" value="YES" name="myradiobutton" />YES<br />
<input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" />
</form>
</BODY>
</HTML>
See this line:
if (isset($_POST['submitit'])) {
If the user presses the submitit button, and javascript is disabled, everything works as expected - the button inserts its name/value pair into the posted data right before the form gets posted, so $_POST['submitit'] is set.
If, however, javascript is enabled, the button doesn't trigger a postback itself, instead it calls a javascript function which posts the form. Unfortunately though, when you call form.submit(), it won't go looking for buttons and add their name/value pairs to the posted data (for various reasons). So you need to find a different way of telling whether you are processing a post-back; the easiest way is to just put a hidden field into your form and check for that, e.g.:
(in the HTML part, somewhere inside the <form></form>):
<input type="hidden" name="is_postback" value="1" />
...and then change your PHP check to:
if ($_POST['is_postback'] == '1')
Change your javascript to:
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
return true; // this line enables the form to submit as normal and is not actually required
}
And remove the "return false;" from the on click event of the button. Having the validation function return false on validation fail is sufficient to stop the from from validating.
This should enable your php to work as is.
I have found many sites that describes PRG, but no simple PHP code example.
Here's what I implemented:
The form.php has an action: validate.php.
The validate.php is never seen by the user; if validates all $_GET and, if valid writes it to database and generates the HTML of a confirmation page / if not valid, it generates the HTML of an error page explaining what is wrong.
Whichever HTML is generated get stored in a $_SESSION variable and then validate.php calls header('Location: <as appropriate>);.
The submitted.php of invalid_input.php (in case the user reads the URL) consists only of echo $_SESSION['form_html'];.
That seems to me like protection against both page reload and back button problems.
Did I goof by trying to reinvent the wheel?
Simplest scenario:
<?php
if ($_POST) {
//validate the input
if (/* input is OK */) {
// Execute code (such as database updates) here.
// Redirect to this page.
header( "Location: {$_SERVER['REQUEST_URI']}", true, 303 );
exit();
}
}
?>
<html>
<!-- here goes your HTML page with a form -->
Use REQUEST_URI. Do not use PHP_SELF as in most CMS systems and frameworks PHP_SELF would refer to /index.php.
A snippet of code:
if (count($_POST)) {
// process the POST data
// your code here- so for example to log a user in, register a new account..
// ...make a payment...etc
// redirect to the same page without the POST data, including any GET info you
// want, you could add a clause to detect whether processing the post data has
// been successful or not, depending on your needs
$get_info = "?status=success";
// if not using rewrite
// header("Location: ".$_SERVER['PHP_SELF'].$get_info);
// if using apache rewrite
header("Location: ".$_SERVER['REQUEST_URI'].$get_info);
exit();
}
Browser
HTML form
method=POST
|
v
PHP app
reads $_POST
sends 303 header
|
v
Browser
receives header
redirected to
new page
|
v
PHP app
reads $_GET
does whatever
A common use is in login authentication. That's the process flow when user submits the login form. PHP app authenticates user via $_POST vars. Sends a 303 header back to browser when the user has successfully authenticated. So user is redirected to a new page.
I would like to introduce you to a method that is often used on a greater scale and in much more detail in frameworks.
What we are going to do
We have a file called index.php.
We are going to submit a form
We are going to check for this submit
We will add the POST data to a session
We will redirect the user to a confirmation page
We will display the data and let the user confirm.
We will submit, and finally process the data.
We will redirect back to index.php and show a notification.
The code
<?php
if (!isset($_SESSION)) session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['submit']) {
case 'add':
// This is where our first POST will end up
// We can perform actions such as checking the data here
// After that we will add the POST data to a session
$_SESSION['postdata'] = $_POST;
// and unset the $_POST afterwards, to prevent refreshes from resubmitting.
unset($_POST);
// Now we will redirect...
header("Location: ".$_SERVER['PHP_SELF']);
break;
case 'confirm':
// We can now insert the data into the database or email it
// Then we will unset the session and redirect back
unset($_SESSION['postdata']);
// This is to display our notification
$_SESSION['success'] = true;
// And there we go again...
header("Location: ".$_SERVER['PHP_SELF']);
break;
}
// We will exit here because we don't want the script to execute any further.
exit;
}
?>
<?php if (isset($_SESSION['success']) && $_SESSION['success'] == true): ?>
<p>Our data has been processed succesfully</p>
<?php unset($_SESSION['success']); ?>
<?php endif; ?>
<?php if (isset($_SESSION['postdata'])): ?>
<p>
You want to add the following data:<br />
<pre><?php print_r($_SESSION['postdata']); ?></pre>
Is this correct?<br />
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<button type="submit" name="submit" value="confirm">Yes</button>
</form>
</p>
<?php else: ?>
<p>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="..."><br />
<input type="text" name="..."><br />
<input type="text" name="..."><br />
<input type="text" name="..."><br />
<button type="submit" name="submit" value="add">Add something</button>
</form>
</p>
<?php endif; ?>
Here is form.php
<?php
session_start();
// 1) _____________________________________________ POST _____________________________
if ( count($_POST) ) {
$ermsg ='';
…
check data, write some data to database(s), set error message(s) if any
…
$userdata1 = $_POST['htUserdata1'];
$userdata2 = $_POST['htUserdata2'];
…
$_SESSION['PRG'] = array('field1'=>$userdata1,'field2'=>$userdata1,…,'ermsg'=>$ermsg);
session_write_close();
header('Location: ' . $_SERVER['REQUEST_URI'].'?z',true,303);
exit;
// 2) _____________________________________________ REDIRECT ________________________
} else if ( array_key_exists('PRG',$_SESSION) ) {
$userdata1 = $_SESSION['PRG']['field1'];
$userdata2 = $_SESSION['PRG']['field2'];
…
$ermsg = $_SESSION['PRG']['ermsg'];
unset($_SESSION['PRG']);
// 3) _____________________________________________ GET ______________________________
} else {
…
retrieve data from database(s)
…
$userdata1 = dbGet1();
$userdata2 = dbGet2();
…
$ermsg = '';
}
// 4) _____________________________________________ DISPLAY _________________________
?>
<!DOCTYPE html>
<html lang="fr">
…
<form method="post" action="form.php" accept-charset="utf-8">
<input id="htUserdata1" name="htUserdata1" type="text"/>
<input id="htUserdata2" name="htUserdata2" type="text"/>
…
</form>
<script language="javascript">
"use strict";
<?php
$G['htUserdata1'] = $userdata1;
$G['htUserdata2'] = $userdata2;
…
$G['ermsg'] = $ermsg;
$myJSON = json_encode($G);
echo "var G=$myJSON;";
?>
document.getElementById('htUserdata1').value = G.htUserdata1;
document.getElementById('htUserdata2').value = G.htUserdata2;
…
if ( G.ermsg !=='') alert(G.ermsg);
</script></body></html>
Caller.htm
<form method="post" action="Callee.php?Query1">
<input type="text" name="PostData" />
<input type="submit" value="Go" />
</form>
Callee.php (Is called twice.)
if ($_POST) {
header("Location: ". $_SERVER['REQUEST_URI']. 'Query2');
// PART1: Use $_POST and $_GET to execute database updates here...
// Now any display (i.e. echo or print) will come after the header.
// ...
die; // When done, GET 'myself' to execute PART2 below.
}
// PART2: Results page goes here...
echo 'PART 2 display output: '; var_dump($_GET);
Notice there are two query strings involved
Look what var_dump says about $_GET:
PART 2 display output: array(1) { ["Query1Query2"]=> string(0) "" }
Issues with putting header at the end of the POST section like this:
header("Location: ". $_SERVER['REQUEST_URI']. 'Query2'); die;
The php manual says: "Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file."
However if you need to build 'Query2' based on what happens in the POST section, it may need to be at the bottom of the POST section. This is ok, so long as you don't try to insert any echo's above it, not even for testing.