PHP contact form keep input fields if error, otherwise clear - php

I want my contact form input fields to save the user's inputs if there's an error, otherwise have them cleared if the email goes through. Right now it works except when the email is sent the fields are still filled in. I could refresh the page but then it doesn't show the 'Your email has been sent' message.
Here's my form:
<form class="contact-form" action="" method="post">
<input type="text" name="name" value="<?php if(isset($_POST["name"])) echo $_POST["name"]; ?>" />
</form>
I tried adding something to my php code that handles the email business - if the message was sent, unset($_POST["name"]), and also adding to this form input's php else echo ''; but that didn't seem to work. It seems the variable was still set.

Let's assume that your page is contact.php.
You php code should be something like this:
// we will keep here error message
$error = '';
// if request is get and isset sent
if ($_SERVER["REQUEST_METHOD"] === "GET" and isset($_GET["sent"]))
echo '<p id="output-area">Message has been sent.</p>';
else {
// if request is post
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// then verify input data
if (!empty($_POST['msg'])) {
// if mail was sent, redirect to contact.php?sent
if (mail("someone#example.com", "My subject", $_POST['msg'])){
header('Location: contact.php?sent');
exit;
} else
$error = "Mail does not sent.";
} else
$error = 'Please fill in all inputs.';
}
}
if ($error != '')
echo '<p class="error">Error: ' . $error . '</p>';
// here goes your form
echo '<form class="contact-form" action="contact.php" method="post">
<textarea name="msg">' . (!empty($_POST["msg"]) ? $_POST["msg"] : '') . '</textarea>
<input type="submit" value="send">
</form>';

You should set error flag while error occurred. try this
$error=false;
if(isset($_POST['submit'])){
$msg = $_POST['msg'];
if(mail("someone#example.com","My subject",$msg)){
}else{
$error = "mail does not sent";
}
}
" />

Related

cant update db on ajax submit php form

I can't update my database table on form submit with ajax. I don't know the reason or why this is happening. I posted my code below. Thanks.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$ime = !empty($_POST['ime']) ? stripslashes(trim($_POST['ime'])) : '';
$email = !empty($_POST['email']) ? stripslashes(trim($_POST['email'])) : '';
$poruka = !empty($_POST['poruka']) ? stripslashes(trim($_POST['poruka'])) : '';
$ime = htmlspecialchars($_POST['ime']);
$email = htmlspecialchars($_POST['email']);
$poruka = htmlspecialchars($_POST['poruka']);
//Validate Phone
if (empty($_POST["ime"])) {
http_response_code(400);
echo "Molimo, unesite Vaše ime i prezime.";
exit;
}else {
if (!preg_match('/^[a-zA-Z\s]+$/',$ime)) {
http_response_code(400);
echo "Dozvoljena su samo slova i space.";
exit;
}
}
//Validate Email
if (empty($_POST["email"])) {
http_response_code(400);
echo "Molimo, unesite Vaš e-mejl.";
exit;
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Nepravilan e-mejl format";
exit;
}
}
if (empty($_POST["poruka"])) {
http_response_code(400);
echo "Molimo, unesite Vašu poruku.";
exit;
}
if(isset($_POST['submit']) && !empty($_POST['ime']) && !empty($_POST['email']) && !empty($_POST['poruka'])){
$link = new mysqli("localhost", "admin", "", "proba");
$stmt = $link->prepare("INSERT INTO message(ime, email, poruka) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $ime, $email, $poruka);
$stmt->execute();
$stmt->close();
$link->close();
$email_message .= "Ime i prezime: ".htmlspecialchars($ime)."\n";
$email_message .= "E-mejl: ".htmlspecialchars($email)."\n";
$email_message .= "Poruka: ".htmlspecialchars($poruka)."\n";
$to = "somemail#mail.com";
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($to, $subject, $email_message, $headers)) {
http_response_code(200);
echo "Poruka je uspešno poslata!";
exit;
} else {
http_response_code(400);
echo "Message is not successfully sent";
exit;
}} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
exit;
}
}
?>
Html
<div class="container">
<h1>Kontakt</h1>
<div id="form-messages"></div>
<form action="mail.php" method="POST" id="form">
<input id="ime" type="text" name="ime" value="<?php echo !empty($ime) ? $ime : ''; ?>" placeholder="Ime i Prezime">
<input id="email" type="text" name="email" value="<?php echo !empty($email) ? $email : ''; ?>" maxlength="20" placeholder="E-mejl">
<textarea name="poruka" id="poruka" placeholder="Poruka" maxlength="700" cols="30" rows="10"><?php echo !empty($poruka)?$poruka:''; ?></textarea>
<input id="submit" type="submit" name="submit" value="Pošalji Poštu">
</form>
</div>
and JQuery
$(function() {
// Get the form.
var form = $('#form');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: 'mail.php',
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#ime').val('');
$('#email').val('');
$('#poruka').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
If anybody has a solution, please do tell. I copied and pasted this amount of code for you to see the context. I don't know where to look for the solution. Thank you.
The reason this does not work via ajax (but does via a conventional postback) is that jQuery's .serialize() method does not serialise button values.
Therefore despite you having name="submit" on your button, its value will not be sent to the server in the request when you make the ajax call. In a conventional postback, it would be, if the button was used as the means to submit the form.
The documentation says:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button.
Although your button click may have triggered the code which submitted the form, it is no longer doing the form submission directly (instead ajax is doing it). In theory this could be triggered by anything, and jQuery has no way of knowing it was the button which started the process.
See https://api.jquery.com/serialize/ for more detail.
This causes you a problem because you test for the presence of this "submit" value before you make your database call and send your email. It's not really necessary to do this, since you're validating all the other input fields. I think you can just remove isset($_POST['submit']) from your if statement and you will have no problems. Therefore you'll be left with:
if(!empty($_POST['ime']) && !empty($_POST['email']) && !empty($_POST['poruka'])) {

Display form validation error message on same page using only PHP?

I'm very new to PHP and I've cobbled this together from some other answers on here. Can anyone show me how to get the $errMsg to display? At present, a blank or incorrect name leads to a blank page. Is this because the form isn't being displayed again? If so, how should I go about 'reloading' the form with the error message?
<?php
$name = "Fred";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["name"])) {
if ($_POST["name"] == $name) {
include("welcomeFred.php");
}
else {
$errMsg = "Incorrect name";
}
}
else {
$errMsg = "Name required";
}
}
else { ?>
<html>
...
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" required>
<span><?php echo $errMsg;?></span>
<input type="submit" value="Submit">
</form>
...
</html>
<?php } ?>
You shouldn't put the rendering of the form in the else of your if structure. This is the reason your form isn't loaded when you submit the form.
Remove the else { ?> and <?php } ?> at the end of your file and it should work fine.

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.

Using $_GET[] causes issues with sending email with mail()

In my website, it presents a list of program titles. When a title is clicked, it displays the content and an email form. The form just takes an email and mails the title as the subject and the content of the page in the email.
The link will pass a variable 'info'. 'info' contains the ID for the post in my database. The problem occurs when I click the submit button. It will not send an email, and refresh the page. This causes the url to loose the 'info' variable and loose all content on the page.
The page works perfectly if I hardcode the ID in the php and don't use $_GET['info'].
Is there something I am missing?
<?php
$id = $_GET['info'];
/*****************************************************
open conection to the mySQL database
******************************************************/
$configs = include('config.php');
//Create a connection
$con = mysqli_connect(
$configs['host'], //host
$configs['username'], //username
$configs['password'], //password
$configs['dbname'] //dbname
);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
/*****************************************************
Populate the page
******************************************************/
$sql="
SELECT p.post_title, p.post_content
FROM they_posts AS p
WHERE p.ID='".$id."'
";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
/*Title*/
echo '<h1>'.$row['post_title'].'</h1><hr>';
/*content*/
echo '<h2>Details: </h2><br>'.$row['post_content'].'<br>';
$title= $row['post_title'];
$content = $row['post_content'];
/*****************************************************
E-mail Form
******************************************************/
include('includes/email_test.php');
}
?>
And this is the email_test.php
<div data-role="collapsible">
<h1>Send Reminder Email</h1>
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
// display form if user has not clicked submit
if (!isset($_POST["submit"]))
{
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Your Email: <input type="text" name="to"><br>
<input type="submit" name="submit" value="Submit Feedback">
</form>
<?php
}
else // the user has submitted the form
{
// Check if the "from" input field is filled out
if (isset($_POST["to"]))
{
// Check if "from" email address is valid
$receivecheck = spamcheck($_POST["to"]);
if ($receivecheck==FALSE)
{
echo "Invalid input";
}
else
{
$to = $_POST["to"]; //receiver
$subject = $title;
$message = $content;
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("$to",$subject,$message,"From: noreply#address.com\n");
echo "reminder has been sent";
}
}
}
?>
</div>
I have used isset($id) to display a back button for when submit is pressed. This will bring back the information but the email is still never sent.
In your scenario you must have info=post_id in your current url to get $_GET['info']
1st way:
Change your form action like this:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"].'?info='.$_GET['info']; ?>">
then in action it will be :
/your_page.php?info=current_post_id
then in action page you can get info by $_GET['info']
2nd way:
or you can add extra hidden form field in your form for post_id like this:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Your Email: <input type="text" name="to"><br>
<input type="submit" name="submit" value="Submit Feedback">
<input type="hidden" name="post_id" value="<?php echo $_GET['info'];">
</form>
After that In your action page you can get post_id by $_POST['post_id']
It should make sense!
Thanks
$_GET['info'] will only work if your form is defined with method='GET'.
If your form is defined with method='POST' then you need to use $_POST['info'].
If you want your code to work no matter whether the form is using GET or POST, then use $_REQUEST['info'].

Using Sessions To Remember User on PHP Form

Intro: I'm trying to learn PHP on $_SESSION. What I was trying to do is call the value assigned through sessions that when you close your tab will keep the value assigned and echoes it on the browser when you open a tab in the browser.
Issue: There's something wrong with my code where for some reason I couldn't echo the value entered in on a form.
The form looks like this:
Name:_____________
Email:_____________ Remember me? __ SUBMIT
I made it so that $_SESSION['name'] = "John" and $_SESSION['email'] = "someemail#email.com" only when user click on "remember me".
If you close a "tab" on the browser but not the browser itself should echo...
John
someemail#email.com
Here's your download link (some link here)...
But of course if you close the browser, session is lost. Cookies can be used but I'm working on sessions to learn more.
Below's code runs but for some reason I couldn't echo values from $_SESSION variables.
<?php
//Start session
session_start();
// session
if (isset($_POST['remember'])) {
$customer_name = $_SESSION['name'];
if (!($customer_name)) {
$customer_name = $_POST['name'];
}
$customer_email = $_SESSION['email'];
if (!($customer_email)) {
$customer_email = $_POST['email'];
}
}
//If form submit validate
if (isset($_POST['Submit'])) {
// Santize fields here but FILTER_VALIDATE_STRING isn't necessary as there is no absolute way
//to validate names absolutely
// Also shows error message if there's error
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
// Sanitize and validate email
// Error message shows if any
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is NOT a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
// If no errors, submitted form is emailed
if (!$errors) {
echo "I did something!<br /><br />"; // might add some message
//downloadLink();
echo "<br /><br />";
}
} else {
echo '<div id="error">' . $errors . '<br /></div>';
}
?>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name:
<?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name']."<br />";
}
else {
?>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="25" /><br />
<?php } ?>
Email:
<?php
if (isset($_SESSION['email'])) {
echo $_SESSION['email']."<br /><br />";
// echo link.. downloadLink();
}
else {
?>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="25"/>
<input type="checkbox" name="remember" /> Remember me
<input type="submit" name="Submit" />
<?php } ?>
</form>
</div>
Put this at the beginning under session_start();
if (!isset($_SESSION['name'])) {
echo "Your session is not good";
} else { echo "Session is set";
}
then replace $customer_name = $_SESSION['name']; with $_SESSION['name']=$_POST['remember']; and you will start getting results.

Categories