html form not submitting and reopening same page - php

I am quite new to programming and am trying to set up a simple test form that is supposed to add or subtract the two numbers given. I have done it several times and it's always worked well. This one, I can't figure out what is wrong. When I hit submit, it reopens the same page in another tab.
Code for the form (html)
<form id="envio" target="formulario2p.php" method="POST">
Ingrese primer valor: <br>
<input type="text" name="valor1" id="valor1" />
<br>
Ingrese segundo valor: <br>
<input type="text" name="valor2" id="valor2" />
<br>
Indique operacion: <br>
<input type="radio" name="radio1" value="suma"/> sumar
<br>
<input type="radio" name="radio1" value="resta"/> restar
<br>
<input type="submit" value="operar"/>
</form>
PHP:
<?php
$valor1=$_POST["valor1"];
$valor2=$_POST['valor2'];
$radio1=$_POST["radio1"];
echo $valor1; echo $valor2;
if($radio1=="suma")
{$suma=$valor1 + $valor2;
echo "la suma es ".$suma;}
else {
$resta=$valor1 - $valor2;
echo "la resta es ".$resta;
}
?>

Specify action:
You are doing:
<form id="envio" target="formulario2p.php" method="POST">
Should be
<form id="envio" action="formulario2p.php" method="POST">
target attribute specifies where to open a new documents. http://www.w3schools.com/tags/att_a_target.asp
action specifies which url to send the form data to. See http://www.w3schools.com/tags/att_form_action.asp

You are missing action in your form. You may try:
<form id="envio" action="formulario2p.php" method="POST">
...
</form>

Related

checkbox does not register PHP

I am trying to make a form. I want to display a message if you have checked the checkbox and when submit it. If the checkbox is not checked, I do not want the massage.
I have tried a lot of things and I have searched a lot but can not make it work.
If I use 'isset', it will never display the message. Not when the box is checked and not when it is not checked.
When I use '!isset' is will always display the message.
Can someone help me?
Thanks
Code:
<?php
if ($_SERVER['REQUEST_METHOD']==='POST' ){
if (isset($_POST['invoeren'])){
echo'Invoer is gelukt';
}
}?>
<form>
<p>
<label for="invoeren">wil je dit invoeren?</label>
<input type="checkbox" id="invoeren" naam="invoeren">
</p>
<p>
<input type="submit" value="submit">
</p>
</form>
You made a typo in the html tag. You should use the English name for the attribute instead of Dutch naam.
Also you should specify method='post' for the form. Otherwise it will use get as default.
<?php
if ($_SERVER['REQUEST_METHOD']==='POST' ){
if (isset($_POST['invoeren'])){
echo'Invoer is gelukt';
}
}?>
<form method='post'>
<p>
<label for="invoeren">wil je dit invoeren?</label>
<input type="checkbox" id="invoeren" name="invoeren">
</p>
<p>
<input type="submit" value="submit">
</p>
</form>

Submit button already clicked

I have a form that I want to submit and I check if any textbox has text so I can UPDATE something in a database.
This is the code for the form:
<form action="" method="POST"/>
CNP Nou: <input type="text" name="cnpN"/><br/>
Nume Nou: <input type="text" name="numeN"/><br/>
Prenume Nou: <input type="text" name="prenN"/><br/>
Data Nasterii Noua: <input type="text" name="dataNN"/> De forma AAAA-ZZ-LL <br/>
Sex Nou: <input type="text" name="sexN"/> F sau M <br/>
Numar Telefon Nou: <input type="text" name="telN"/><br/>
Adresa Noua: <input type="text" name="adrN"/><br/>
E-mail Nou: <input type="text" name="mailN"/><br/>
<input type="submit" value="Modifica" name="search2" class="submit" />
</form>
Then I check if the button is clicked so I can see if any textbox has text written in order to make an UPDATE in my database:
if (isset($_POST["search2"]))
{
if (!empty($_POST['cnpN']) || !empty($_POST['numeN']) || !empty($_POST['prenN']) || !empty($_POST['dataNN']) || !empty($_POST['sexN']) || !empty($_POST['telN']) || !empty($_POST['adrN']) || !empty($_POST['mailN']))
{
//php code for update
}
}
else
{
echo "<h4><b> Eroare! </b><h4>";
}
The problem is that without clicking the button I see the "Eroare!" message. If I remove that else statement and I click the button nothing happens to the database, even if I introduce something in the form.
I used the else statement just to see if that might be the problem or not.
I am looking through the code for some time and can't see the problem.
I know there are simpler ways to check the completed textboxes but I'm new to php and I thought it's easier this way.
The else clause belongs on the if not empty conditional.
When you first load the php script, there is no POST data present. That is expected since it is a GET request. This is why the initial conditional is false and the error message appears. POST will never be set on an HTTP GET request.
Submit button is not already clicked , but your code is outputting 'Eroare' because, initially, you don't have set any post data on page load, including search2. So you don't need else part of conditional unless you mark that an error occurred, but within the if(isset($_POST["search2"])){} block.
Otherwise, it will always output the 'Eroare'.
You first need to validate your form data, then to throw the error if any of form data doesn't fulfill the conditions.
About validation process, you would either need to implement some existing validation libraries or to extend your conditional to check for specific data, specific validation requirements.
Some of them would be required (not empty), some of them would require constrained/limited values from a list ( like gender field ), some would require number value validation ( phone ), an email field would require email value validation.
Also, you are missing the part for DB insertion.
Simplified code without advanced validation would be like this:
<?php
$post_search2 = filter_input(INPUT_POST,'search2'); //filter_input returns empty if input not set, and it is useful to filter and validate specific values;
if(!empty($post_search2))
{
$form_values = array('cnpN', 'numeN', 'prenN', 'dataNN', 'sexNN', 'telN', 'adrN', 'mailN'); //I have placed it in array to avoid having large code and simplify checks through iteration
$parsed_data = array();
foreach($form_values as $form_value){
$value = filter_input(INPUT_POST, $form_value);
if(!empty($value)){ //update parsed data only if form data is not empty
$parsed_data[$form_value] = $value;
}
}
//so if any of data is filled, do the updates
//this actually does same as !empty($_POST['cnpN']) || !empty($_POST['numeN']) || !empty($_POST['prenN']) && ...
// if you would require all data filled, check if count($parsed_data) === count($form_values) and that actually does same as this actually does same as !empty($_POST['cnpN']) && !empty($_POST['numeN']) && !empty($_POST['prenN']) && ...
//
if(count($parsed_data) > 0){
//php code for update
}else{
echo "<h4><b> Eroare! </b><h4>";
}
}
?>
<form action="" method="POST">
CNP Nou: <input type="text" name="cnpN"/><br/>
Nume Nou: <input type="text" name="numeN"/><br/>
Prenume Nou: <input type="text" name="prenN"/><br/>
Data Nasterii Noua: <input type="text" name="dataNN"/> De forma AAAA-ZZ-LL <br/>
Sex Nou: <input type="text" name="sexN"/> F sau M <br/>
Numar Telefon Nou: <input type="text" name="telN"/><br/>
Adresa Noua: <input type="text" name="adrN"/><br/>
E-mail Nou: <input type="text" name="mailN"/><br/>
<input type="submit" value="Modifica" name="search2" class="submit" />
</form>
Just remove the close tag from the form tag
ie, change <form action="" method="POST"/> to <form action="" method="POST">
If it doesn't solve your issue then use the following code snippet,
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
CNP Nou: <input type="text" name="cnpN"/><br/>
Nume Nou: <input type="text" name="numeN"/><br/>
Prenume Nou: <input type="text" name="prenN"/><br/>
Data Nasterii Noua: <input type="text" name="dataNN"/> De forma AAAA-ZZ-LL <br/>
Sex Nou: <input type="text" name="sexN"/> F sau M <br/>
Numar Telefon Nou: <input type="text" name="telN"/><br/>
Adresa Noua: <input type="text" name="adrN"/><br/>
E-mail Nou: <input type="text" name="mailN"/><br/>
<input type="submit" value="Modifica" name="search2" class="submit" />
</form>
PHP Code
if(isset($_POST["search2"]))
if(!empty($_POST['cnpN']) || !empty($_POST['numeN']) || !empty($_POST['prenN']) || !empty($_POST['dataNN']) || !empty($_POST['sexN']) || !empty($_POST['telN']) || !empty($_POST['adrN']) || !empty($_POST['mailN']))
{
//php code for update
}
Your code is working perfectly normal, output is showing because in the begining the "form" is not submitted and "if" it is not submitted then "else" should work and "else" is working. if you don't want it to be shown then you can remove else.it will work fine, also try not to end the form tag early
instead of
<form action="" method="POST"/>
use this
<form action="" method="POST"> `

Why are the nested forms processed with $_SERVER['PHP_SELF'] (same html file) not displaying/processing correctly?

I'm trying to get user input in a progressive sequence that leads to that input being sent by email. Sending by email is a whole other issue that I haven't tackled yet so not really worried about that.
The part I am having difficulty with is once the user gets to the "Send Email?" (Yes/No) radio buttons, the input from that question is not processed correctly.
I've gotten further with this by using a separate php file as the form action but still get errors related to emailName, emailAddress, and emailMsg not existing ("Notice: Undefined index...").
Furthermore, I still need to be able to use the $_POST[athletes] array further down but I'm guessing it's outside of the variable scope at that point.
So to bring that all together, I'm really asking a few questions:
1) How can I get all of the forms to work together in the same file?
2) When the program actually goes past the "Send Email?" radio buttons when I use a separate php file as the form action, why am I getting undefined index errors?
3) Why do I get an error when I try to use the athletes[] array further down in the code? Should I somehow be passing the array values to that part of the code?
The exact steps the user would take to get to the issue is:
Select 1 or more athlete checkboxes and click the 'Display Selection(s)' button.
Select 'Yes' for "Send Email?" and click the 'Submit' button.
Restarts the code for some reason.
Any help would be greatly appreciated. Also, this is my first post so sorry if I asked the question incorrectly or not according to site etiquette.
I also apologize for the long code fragment but I'm not sure what parts might be causing this to be incorrect.
<b><h1><center>Athelete Selection Screen</center></h1></b>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<fieldset>
<legend>Athletes Available: </legend>
<input type="checkbox" id="student1"
name="athletes[]" value="Student1 Test">
<label for="student1">Student1 Test</label><br/>
<font color="grey">Football - Running back</font><br/>
<p>
<input type="checkbox" id="student2"
name="athletes[]" value="Student2 Test">
<label for="student1">Student2 Test</label><br/>
<font color="grey">Soccer - Left Forward</font><br/>
</p>
<p>
<input type="checkbox" id="student3"
name="athletes[]" value="Student3 Test">
<label for="student1">Student3 Test</label><br/>
<font color="grey">Baseball - Pitcher/Left Outfield</font><br/>
</p>
</fieldset>
<p>
<?php echo("\t\t\t\t\t"); ?><button type="submit" name="submit" value="submit">Display Selection(s)</button>
</p>
</form>
<fieldset>
<legend>Athletes You Selected: </legend>
<?php
if (!empty($_POST['athletes']))
{
echo "<ul>";
foreach($_POST['athletes'] as $value)
{
echo "<li>$value</li>";
}
echo "</ul>";
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<fieldset>
<legend>Send Email? </legend>
<input type="radio" id="Yes"
name="radioSendMsg[]" value="Yes">
<label for="student1">Yes</label>
<p>
<input type="radio" id="No"
name="radioSendMsg[]" value="No">
<label for="student1">No</label><br/>
</p>
<button type="submit" name="submitRadio" value="submit">Submit</button>
</p>
</form>
<?php
if (!empty($_POST['radioSendMsg']))
{
foreach($_POST['radioSendMsg'] as $radioMsg)
{
if($radioMsg == "Yes")
{
echo "\tPlease enter information regarding the email to be sent: ";
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<label for="emailName"> Name: </label><br/>
<input type="text" size="25" id="emailName" name="emailName" />
</p>
<p>
<label for="emailAddress">E-mail Address: </label></br>
<input type="text" size="25" id="emailAddress" name="emailAddress" />
</p>
<p>
<textarea id="emailMsg" name="emailMsg" cols="30" rows="5"></textarea>
</p>
<button type="submit" name="emailSubmit" value="send">Send Message</button>
</form>
<?php
$msg = "Name: ".$_POST['emailName']."\n";
$msg.= "E-Mail: ".$_POST['emailAddress']."\n";
$msg.= "Message: ".$_POST['emailMsg']."\n";
$msg.= "<ul>";
foreach($_POST['athletes'] as $value)
{
$msg.= "<li>$value</li>\n";
}
$msg.= "</ul>";
$emailRecipient = "sjzerbib#gmail.com";
$emailSubject = "Athlete Selection Submission";
$emailHeaders = "From: Sebastien\n"."Reply-To: ".$_POST['emailAddress'];
mail($emailRecipient,$emailSubject,$msg,$emailHeaders);
echo "Message sent: \n".$msg;
}
else
{
?> <p /> <?php
echo "\n\nNo email will be sent for your last athlete selection.";
?>
<br/>Please click here
to return to the Athlete selection screen.
<?php
}
}
}
}
When you submit a form, only those controls contained within that form are included. The exception is successful controls that have the form attribute set to the id value of the form that was submitted.
So, given you had something like:
<form id="form-1" method="post">
<input type="text" name="first-input" />
</form>
<input type="text" name="second-input" />
The only value to be submitted would be that of first-input. If you add the form attribute to second-input:
<input type="text" name="second-input" form="form-1" />
Then the submission of the form would include both values. Unfortunately, the form attribute is not fully supported (IE and Edge have no support).
Of course, your markup is invalid, so that's a moot point. For starters, you cannot nest a form within a form. How a browser responds to markup that violates that rule is up to it's vendor, but in my experience is somewhat unpredictable. You're also using deprecated tags (<font> and <center> are no longer valid) and nesting elements incorrectly (<h1> is a block level element, whereas <b> is inline).
If you're doing a full submit each time (so the page gets submitted to itself and then reloads), then just use some sort of conditional to only render the dependent controls if the preceding form submissions were successful:
<?php
$canDoNextStep = !empty($_POST['input-1']);
?>
<form id="form-1" method="post">
<input type="text" name="first-input" />
<?php if(canDoNextStep): ?>
<input type="text" name="second-input" />
<?php endif; ?>
</form>
Lastly, whitespace is (mostly) ignored when your browser parses and displays your HTML, so you can lose the \t and \n values in your strings, unless you're concerned about how your markup looks if someone chooses to view source when using your form.

Redirecting to the other page after submitting radio button option

I have a problem with my form. I need it to redirect user to different pages basing on which radio button was selected. User has to choose one of two options and click next, and according to his choice, page should redirect him to other page.
Here is the code as it looks for now
<fieldset>
<legend>Select option</legend>
<center>
<form method="post" action="">
<input type="radio" name="radio1" value="Osoba fizyczna"/>Non-company
</br>
<input type="radio" name="radio2" value="Firma"/>Company
</br>
<input type = "submit", class = "buttonStyle2", value=""/>
</form>
</center>
</fieldset>
and then php code
if(isset($_POST['Company'])
header("Location: http://myaddress.com/company.php");
Big thanks in advance for your help
Here is one way to achieve this.
Sidenote: Make sure you're not outputting before header. Consult this page on Stack about possible Headers already sent..., should this occur and making sure error reporting is set/on.
Otherwise, PHP will fail silently.
if(isset($_POST['radio1']) && ($_POST['radio1']) == "Osoba fizyczna"){
header("Location: http://www.example.com/non_company.php");
}
elseif(isset($_POST['radio1']) && ($_POST['radio1']) == "Firma"){
header("Location: http://www.example.com/company.php");
}
else{
header("Location: http://www.example.com/redirect_to_home.php");
}
Nota: The else would be if the person did not make a choice and simply clicked on submit without making a selection.
while using radio buttons of the same group name in your form:
<input type="radio" name="radio1" value="Osoba fizyczna"/>Non-company
</br>
<input type="radio" name="radio1" value="Firma"/>Company
Note about
<input type = "submit", class = "buttonStyle2", value=""/>
remove the commas
<input type = "submit" class = "buttonStyle2" value=""/>
Since HTML source in FF will reveal No space between attributes in red/as an error.
<fieldset>
<legend>Select option</legend>
<center>
<form method="post" action="">
<input type="radio" name="radio1" value="Osoba fizyczna"/>Non-company
</br>
<input type="radio" name="radio1" value="Firma"/>Company
</br>
<input type = "submit" class = "buttonStyle2" value=""/>
</form>
</center>
</fieldset>
and
if ( isset($_POST['radio1']) ) {
$filename = $_POST['radio1'] . "php";
header("Location: http://myaddress.com/".$filename);
}
Might be even better to set up an array with allowed values and check if radio1 is in that array.

How to send a result to a form with php?

I'm really new to PHP but it's awesome language :)
I created simple mathematical calculation script that takes inputs from forms in terms of variables and perform simple calculations. I would like a result to be displayed in another form instead of simply being displayed at the bottom of the page.
<html>
<body>
<p>Simple PHP script for cloning calculations</p>
<form name="form1" method="post" action="">
<p>
<label for="vector_lenght">La taille du vecteur (kb)</label>
<input type="text" name="vector_lenght" id="vector_lenght">
</p>
<p>
<label for="insert_lenght">La taille de l'insert (kb)</label>
<input type="text" name="insert_lenght" id="insert_lenght">
</p>
<p>
<label for="conc_insert">La concentration de l'insert</label>
<input type="text" name="conc_insert" id="conc_insert">
</p>
<p>
<input type="submit" name="ratio_calc" id="ratio_calc" value="Calculer">
</p>
<p>
<label for="ratio">Le ratio à utiliser</label>
<input type="text" name="ratio" id="ratio">
</p>
<p>
<label for="ratio_1">ratio 1:1</label>
<input type="text" name="ratio_1" id="ratio_1">
<br>
<label for="ratio_3">ratio 1:3</label>
<input type="text" name="ratio_3" id="ratio_3">
<br>
<label for="ratio_5">ratio 1:5</label>
<input type="text" name="ratio_5" id="ratio_5">
</p>
</form>
<?php
if($_POST['ratio_calc']!=''){
define("conc_vector", 100);
$vector_lenght = $_POST['vector_lenght'];
$insert_lenght = $_POST['insert_lenght'];
$conc_insert = $_POST['conc_insert'];
$result = (conc_vector * $insert_lenght) / $vector_lenght;
echo "<h1>$result</h1>";
}
?>
</body>
</html>
In your opening form tag, the 'action' attribute specifies what file should receive the HTTP request created when you submit the form. As it is now the value is an empty string, and the script is defaulting to POSTing the data back to the current script.
(I assume this other form is in a different page - if not, skip to the last code snippet)
So, create another PHP script that represents the page you want to contain your results, and put the name of the new script as the value of the 'action' attribute. In the new script, you can retrieve the values sent by your form via the $_POST[] superglobal (in the same way that you already are in the code you posted).
If the new page is named resultPage.php (and is in the same directory as the script you posted), your form tag should look like this:
<form name="form1" method="post" action="resultPage.php">
If you want the data to display inside a form in the new page, do something like this:
<input type="text" value="<?php echo $_POST['conc_insert'] ?>">

Categories