PHP form error issue - php

There is probably a simple solution for this but i'm not very proficient in php! Basically I want to submit a form and the user be returned with a thank you overlay image without refresh. I've managed to get this to work BUT now the form validating isn't working properly...
I need to make my overlay only appear after the form validating is successful, if it isn't successful I need to display the error instead of the thank you overlay...
I know I could use ajax for this form but I don't want to rely on javascript!
At the minute the validating is working, but the image is being overlayed on top of it...
This is php code:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter your name</li>";
}
if(empty($_POST['formTown']))
{
$errorMessage .= "<li>You forgot to enter your town</li>";
}
$varName = $_POST['formName'];
$varTown = $_POST['formTown'];
$varAge = $_POST['formAge'];
$varEmail = $_POST['formEmail'];
$varOne = $_POST['hidden-one'];
$varTwo = $_POST['hidden-two'];
$varThree = $_POST['hidden-three'];
$varFour = $_POST['hidden-four'];
$varFive = $_POST['hidden-five'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,"\n" . $varName . ", " . $varTown . ", " . $varAge . ", " . $varEmail . ", " . $varOne . $varTwo . $varThree . $varFour . $varFive);
fclose($fs);
}
}
?>
This is my html (with the php code):
<?php
if (isset($_POST['formSubmit'])) {
print "<div class=\"thank-you\"><a href='enter.php'><img src='images/thankyou-overlay.png'/></a></div>\n";
}
?>
<div id="mainContainer">
<p>Just complete your entry details below.</p>
<?php
if(!empty($errorMessage)) {
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" target="_self">
<div class="inputContainer">
<label class="text" name="name">Full Name:</label>
<input type="text" class="box" name="formName" value="<?=$varName;?>">
</div>
... more html inputs...
</form>

Whatever you are going to do, you have to use Javascript. You can choose AJAX either using an iframe where you direct your post to, and reading it in a javascript to check status of posting.
Edit:
Like this you can post it:
<form action="do_stuff.aspx" method="post" target="my_iframe">
<input type="submit" value="Do Stuff!" />
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
So after the post, you have to read status from this iframe, (in other words de HTML output from it).

First , i am having difficulty comprehending what you are trying to do : But still i can point out a few things that have better alternates ;
You should put this code
if($_POST['formSubmit'] == "Submit")
{
...
}
above the form for the functionality you want
and also the above if should have an else to show the form when there are errors.
like
else
{
---form---
}
try this and c if it helps

Related

Display form after submit in PHP/HTML?

Using the code below, I'm having trouble with showing form responses on submit. I've tried a mix of _GET and _POST, but I don't understand what to use and when because I'm relatively new to PHP. How could the code show form responses on submit?
<?php {
$fDogErr = $lDogErr = "";
// only show the information if the button named "subButton" has been pressed
if (!isset($_POST['submit'])) {
// set the variable with the submitted value
if (empty($fDog = $_POST['favourite dog'])) {
$fDogErr = "Need favourite dog";
} else {
$fDog = $_POST['favourite dog'];
}
if (empty ($lDog = $_POST['least favourite dog'])) {
$lDogErr = "Need least favourite dog";
} else {
$lDog = $_POST['least favourite dog'];
}
if (empty($password = $_POST['pawsword'])) {
$password = "";
} else {
$password = $_POST['password'];
}
if (empty($dogcac = $_POST['dogcac'])) {
$dogcac = "";
} else {
$dogcac = $_POST['dogcac'];
}
$secretdoggo = $_POST['secretdoggo'];
}
// display the user inputs to the screen
echo "<p>Your favourite dog is <b>" . $fDog . "</b>.</p>";
echo "<p>Your least favourite dog is <b>" . $lDog . "</b>.</p>";
echo "<p>Your pawsword is <b>" . $password . "</b>.</p>";
echo "<p> Did you know? <b>" . $secretdoggo . "</b>.</p>";
}
?>
You need to have an HTML form with all the input tags defined first. The form tag has an action attribute that states where the data will be sent (the PHP you linked), a method (POST, GET etc..) and a button with type submit that triggers the sending of the form data. The PHP file can then show your form responses when the submit button is clicked.
See the example below:
Form HTML Example:
<form method="post" action="response.php">
<label>Password:</label> <input type="text" id="favourite_dog" name="favourite_dog" />
<label>Password:</label> <input type="password" id="password" name="password" />
more input tags . . .
<button type="submit">Submit</button>
</form>
PHP Example Showing Responses:
response.php
<?php
if (!empty($_POST)){
$favourite_dog = $_POST['favourite_dog'];
$password= $_POST['password'];
echo "<p>Your favourite dog is <b>" . $favourite_dog . "</b>.</p>";
}
Hope this helps.

How to write to file with same name as HTML form field

I have made an attempt to write a PHP code that takes the contents of an HTML form then write them into a file. I have that down just fine, but I have another problem. I want to take an input of a field in the form and make it the file name that I am writing to.
Here is my PHP code:
<?php
if(isset($_POST['forwhom']) && isset($_POST['importance']) && isset($_POST['message'])) {
$file = "students.html";
$data = nl2br('-' . $_POST['forwhom'] . ':' . ' ' . $_POST['message'] . ' ' . $_POST['importance'] . "\n");
$ret = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "Success! Student added to database.";
}
}
else {
die('no post data to process');
}
?>
Currently, I am writing to the file "students.html" However, I want to write to the file "Dad.html", which happens to be the input in the field by the name of forwhom.
Basically, I am asking this: What do I use to replace "students.html" (line 3) so that the file name will be the same as the input of the field forwhom?
I apologize if that didn't make any sense. Thank you very much!
First check if data has been posted on your form using $_SERVER['REQUEST_METHOD'] == "POST".
For simplicity sake save all your "POST" requests in a variable eg.
$file = $_POST['forwhom'];
$importance = $_POST['importance'];
$message = $_POST['message'];
I sometimes find it much easier using empty() instead of isset().
Create a variable, lets say $status which would store all your messages, then any where in your HTML section you just use the $status to display the appropriate message to the user. Check below how i make use of $status in the form.
By doing so is much cleaner and makes your code more dynamic in a sense.
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$file = $_POST['forwhom'];
$importance = $_POST['importance'];
$message = $_POST['message'];
if (!empty($file) && !empty($importance) && !empty($message)) {
$data = nl2br('-' . $file . ':' . ' ' . $message . ' ' . $importance . "\n");
$file .= ".html";
$ret = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
if ($ret == true) {
$status = "Success! Student added to database.";
} else {
$status = "Error writing to file!";
}
} else {
$status = "Please enter name, email and message";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post">
<ul>
<li>
<label for="name">Name: </label>
<input type="text" name="forwhom" id="forwhom">
</li>
<li>
<label for="email">Email: </label>
<input type="text" name="importance" id="importance">
</li>
<li>
<label for="message">Your Message: </label><br>
<textarea name="message" id="message"></textarea>
</li>
<li>
<input type="submit" value="Go!">
</li>
</ul>
<?php if(isset($status)): ?>
<p><?= $status; ?></p>
<?php endif; ?>
</form>
</body>
</html>
I added a form just for explanation sake, hope it helps.

Clear form fields after a successful submit

well im working on a small html form.
<form class="contact" action="" method="POST">
<label>Name : </label><input type="text" name="name" value="<? echo $name; ?>"/>
<p class="middle"><label>Comment : </label><textarea name="message"></textarea><? echo $message; ?></p>
<label class="captcha"><img src="captcha.php" style="line-height: 30px;"></label><input type="text" name="code"/>
<input type="submit" class="csubmit" value="Now !" name="get"/>
</form>
and this is the php code:
<?php
if (isset($_POST['get'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "no name. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "no message <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "wrong captcha <br />";
}
if (!empty($error)) {
echo '<p class="error">Error :<br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
if (empty($error)) {
$message = mysql_real_escape_string($message);
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($_GET['id']);
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO comments(id, name, comment, time,approved)VALUES('$id', '$name', '$message', '$date', '0')");
echo "thank you";
}
}
?>
As you can see i user $message and $name to keep informations after a submit with wrong captcha code, but the problem is that i want to clear those fields after a submit with correct informations. Can you please tell me how can i clear form fields after a succesfull submit ?
You can use .reset() on your form.
$("#form")[0].reset();
You could follow that with Javascript too
document.getElementById('form').reset();
Or, if successful, redirect the user back to your contact page:
header("Location: contact.php"); // redirect back to your contact form
exit;
EDIT
<input type="submit" class="csubmit" value="Now !" name="get" onClick="clearform();" />
function clearform()
{
document.getElementById("name").value=""; //don't forget to set the textbox ID
document.getElementById("message").value=""; //don't forget to set the textbox ID
document.getElementById("code").value=""; //don't forget to set the textbox ID
}
Also use:
required="required"
so people will be required to fill out the input fields :)
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.

$outputstring error with html class

So I'm not that great at php and I have a basic comment system that I'm trying to implement that calls and writes to a comments.php file.
everything works all well an good until I try and style the $outputstring a bit.
this is the code I have
$outputstring = "<br><p><span class="label">Name:</span> " .$name. "</p><br> <p><span class="label">Comment:</span>" .$message. "</p><br>";
I know whats causing it is the
<span class="label"></span>
but can anyone tell me why?
the script I got was just one off youtube while im experimenting with site building.
the full script is like this.
<?php
$act = $_POST['act'];
if($act == "post") {
$name = $_POST['name'];
$message = $_POST ['message'];
#$fp = fopen("comments.php", 'a');
if (!$fp) {
//The file could not be opened
echo "There was an error! Please try again later!";
exit;
} else {
//The file was successfully opened, lets write the comment to it.
$outputstring = "<br><p><span class="label">Name:</span> " .$name. "</p><br> <p><span class="label">Comment:</span>" .$message. "</p><br>";
//Write to the file
fwrite($fp, $outputstring, strlen($outputstring));
//We are finished writing, close the file for security / memory management purposes
fclose($fp);
//Post the success message
echo "Your post was successfully entered. Click <a href='index.php'>here</a> to continue.";
}
} else {
//We are not trying to post a comment, show the form.
?>
<h3>comments:</h3>
<hr/>
<?php include("comments.php"); ?>
<br><br>
<h3>Post a comment:</h3>
<form action="index.php" method="post">
<label>Name:<label>
<input type="text" name="name" value=""></input>
<br/>
<label>Comment:</label>
<textarea name="messages"></textarea>
<input type="hidden" name="act" value="post"></input>
<br/>
<input type="submit" name="submit" value="Submit"></input>
</form>
<?php
}
?>
If anyone could tell me what I would need to do to be able to add the span with a class that would be swell.
thanks.
$outputstring = "<br><p><span class="label">Name:</span> " .$name. "</p><br> <p><span class="label">Comment:</span>" .$message. "</p><br>";
This line is wrong because you break your line delimiters.
Use simple quotes instead of double quotes for the class attribute :
$outputstring = "<br><p><span class='label'>Name:</span> " .$name. "</p><br> <p><span class='label'>Comment:</span>" .$message. "</p><br>";
Or, as stated by chandresh_cool, escape your double quotes.
You cannot use double quotes inside double quotes until you escape them with backslashes, in this case use single quotes instead like this
$outputstring = "<br><p><span class='label'>Name:</span> " .$name. "</p><br> <p><span class='label'>Comment:</span>" .$message. "</p><br>";
$outputstring = '<br><p><span class="label">Name:</span> ' .$name. '</p><br> <p><span class="label">Comment:</span>' .$message. '</p><br>'; This should solve your problem use '' when you don't have dynamic values.

Simple PHP form not working

I´m trying to make a form that works. I´m using codeigniter, the view has this form:
<form class="renuncia_form" action="/formulario/send_form" method="post">
<p>
<label for="nombre">Nombre y apellidos:</label>
<input name="nombre" type="text" id="renuncia_nombre">
<br>
<label for="participe">Nº Partícipe: </label>
<input name="participe" type="text" id="renuncia_participe">
<br>
<label for="nombre_fondo">Nombre del Fondo de Inversión o SICAV: </label>
<input name="nombre_fondo" type="text" id="renuncia_fondo">
<br>
<label for="email">Direccion de correo electrónico: </label>
<input name="email" type="text" id="renuncia_email">
<br>
<input type="submit" value="Enviar" class="renuncia_submit" name="enviar">
</p>
</form>
And the controller has this php:
public function send_form(){
if($_POST['submit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['nombre']))
{
$errorMessage .= "<li>You forgot to enter your name</li>";
}
if(empty($_POST['participe']))
{
$errorMessage .= "<li></li>";
}
$varMovie = $_POST['nombre'];
$varName = $_POST['participe'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varName . ", " . $varMovie . "\n");
fclose($fs);
header("Location: thankyou.html");
exit;
}
}
}
I don´t know if I´m doing correctly the form. I just want to work it as a normal form action, that you click on submit an it takes you to a new page saying "Thanks for your email", no AJAX, just that.
Can anybody help me out with this one?
Edit: Also where do I put the recipient e-mail?
if($_POST['submit'] == "Submit")
should be
if(isset($_POST['enviar']))
As submit button is not having name as submit, instead it is name='enviar'
try this
if(isset($_POST["enviar"]) && $_POST["enviar"] == "Enviar")
You've got
if($_POST['submit'] == "Submit")
and then everything else if the condition is satisfied. It is never as there isn't such field. Just remove it and it'll be fine.
As for mail, you should access it via $_POST['email']. If you want to send an email, take a look here or here.
I think this is because you are translating your form anyway you used
if($_POST['submit'] == "Submit")
and you used in form
<input type="submit" value="Enviar" class="renuncia_submit" name="enviar">
your actual submit button name is enviar and not submit. Since this is a button I would reccomend to check isset()
if(isset($_POST['enviar']))
I'm not sure but the problem is the action attribute.
why don't use From helper to create this form?. Anyway if you don't what or can't use it change the action to something like http://localhost/your_project/index.php/formulario/send_form.
read about base_url here http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html
Besides if($_POST['submit'] == "Submit") is wrong. It must be
if(isset($_POST['submit']) && ($_POST['submit'] === "Enviar"))
if (isset($_POST['enviar']))
This should work
Use:
public function send_form(){
if(array_key_exists('submit',$_POST))
{
$errorMessage = "";
if(empty($_POST['nombre']))
{
$errorMessage .= "<li>You forgot to enter your name</li>";
}
if(empty($_POST['participe']))
{
$errorMessage .= "<li></li>";
}
$varMovie = $_POST['nombre'];
$varName = $_POST['participe'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varName . ", " . $varMovie . "\n");
fclose($fs);
header("Location: thankyou.html");
exit;
}
}
}

Categories