PHP email validation not working properly - javascript

I'm using radio buttons to display my form's textbox. I added a PHP script to validate the email and on completion, open another page. But nothing seems to be working. It shows the error message for when the textbox is empty, even when the submit button hasn't been pressed, and it refreshes the page if the email format isn't correct.
Here's my code:
<?php
// define variables and set to empty values
$emailErr = "";
$email = "";
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
else{
header("Location:create.php")
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
function ShowHideDiv() {
var chkYes1 = document.getElementById("chkYes1");
var dvtext1 = document.getElementById("dvtext1");
var chkYes2 = document.getElementById("chkYes2");
var dvtext2 = document.getElementById("dvtext2");
var button = document.getElementById("button");
dvtext1.style.display = chkYes1.checked || chkYes2.checked ? "block" : "none";
dvtext2.style.display = chkYes2.checked ? "block" : "none";
btn1.style.display = chkYes1.checked ? "block" : "none";
btn2.style.display = chkYes2.checked ? "block" : "none";
}
<div class="content login-container">
<div class="form-login">
<label for="chkYes1">
<input type="radio" id="chkYes1" name="chk" onclick="ShowHideDiv()" />
I am new on Swadonline
</label>
<br>
<br>
<div id="dvtext1" style="display: none" class="lgntxt">
Please enter your Email Address *
<br>
<input type="text" id="txtBox" name="email" />
</div>
<button style="display: none" id="btn1" class="btn third" type="submit" name="submit" value="Submit">CONTINUE</button>
</div>
</div>

In html change this line
<button style="display: none" id="btn1" class="btn third" type="submit" name="submit" value="Submit">CONTINUE</button>
to
<input type="submit" style="display: none" id="btn1" class="btn third" name="my_form_submit" value="CONTINUE">
Now in your php change as below:
<?php
// define variables and set to empty values
$emailErr = "";
$email = "";
if(isset($_POST['my_form_submit'])){ // only check validation if form has been submitted, else don't validate
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
else{
header("Location:create.php");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>

I've taken this route for form submissions once upon a time, since then I would highly recommend setting up PHPMailer for any project.
For the email part: PHPMailer is relatively easy to set up and has never let me down.
For the Validation, all you have to do is add a 'required' attribute to the forms, to my knowledge, the browser will do the rest :)
Hope this in any way helps!

Related

Multipe action="" attribute urls

I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?
HTML:
<form action="<?php echo htmlspecialchars($_server['php_self']);?>
, mailto:example#gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> <label for="first">First Name:</label>
<input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><span class="error"><?php echo $fnameErr;?>
</span><br/>
<label for="last">Last Name:</label>
<input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><span class="error"><?php echo $lnameErr;?>
</span><br/>
<label for="mail">Email:</label>
<input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><span class="error"><?php echo
$emailErr;?>
</span><br/>
<label for="yearLevel">Year Level:</label>
<select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
<option>Year 8</option>
<option>Year 9</option>
<option>Year 10</option>
<option>Year 11</option>
<option>Year 12</option>
<option>Uni Student</option>
<option>Other</option>
</select>
<label for"comment">Comment:</label>
<textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
</textarea><br/><br/>
<input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>
PHP:
<?php
//feedback form validation code
//start
//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";
//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "* Your first name is required!";
} else {
$firstName = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
$fnameErr = "* Only letters and white space allowed!";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "* Your last name is required!";
} else {
$lastName = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
$lnameErr = "* Only letters and white space allowed!";
}
}
if(empty($_POST["comment"])) {
$comment = "* the comment box is required!";
} else {
$comment = test_input($_post["comment"]);
}
if (empty($_POST["email"])) {
$emailErr = "* Your email is required!";
} else {
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Invalid Email Format!";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//end
?>
JS script for a confirm when the user clicks submit. so it makes sense to the form.
<script type="text/javascript">
//confrim before submitting.
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
return true;
} else {
console.log("edit!");
return false;
}
}
</script>
You couldn't add multiple actions in the form action, You should send the form to a PHP file and then after validating, send the email by PHP mail function or other libraries like PHPmailer etc.
Simple answer: No, you cannot add multiple actions for tag, how you would the distinguish between which one to choose?
If you need to select different actions according to some configuration on form choices (or whatever), use Javascript to set new action of form.
In your case, use mail PHP function to send mail from PHP script when you pass your validation.
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" name="feedbackForm" id="ff" class="feedback">
and then in PHP
mail('somebody#example.com', 'Subject', 'Body', optionalHeaders);
You can't do it, but you can call mailto inside your ask() like,
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
// add mailto here
myWindow=window.open("mailto:example#gmail.com");
myWindow.close();
return true;
} else {
console.log("edit!");
return false;
}
}
And change form action like,
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" ...>
....
</form>

checked term and condition before submit form

if user want to submit their form, they have to checked the terma and condition box first.
so where should i add the code?
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = "";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</form>
</fieldset>
</form>
</div>
</body>
</html>
and so here is my userdetail.php to get user data...
<?php
session_start();
$forename = $_SESSION['forename'];
$surname = $_SESSION['surname'];
$email = $_SESSION['email'];
$postalAddress = $_SESSION['postalAddress'];
$landLineTelNo = $_SESSION['landLineTelNo'];
$mobileTelNo = $_SESSION['mobileTelNo'];
$sendMethod = $_SESSION['sendMethod'];
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
if($_SESSION['postalAddress']==NULL)
{echo "<p>postalAddress:NULL</p>";}
else {echo "<p>PostalAddress : $postalAddress </p>";}
if($_SESSION['email']==NULL)
{echo "<p>email:NULL<p/>";}
else {echo "<p>email : $email</p>";}
if($_SESSION['landLineTelNo']==NULL)
{echo "<p>landLineTelNo:NULL<p/>";}
else {echo "<p>landLineTelNo : $landLineTelNo </p>";}
if($_SESSION['mobileTelNo']==NULL)
{echo "<p>mobileTelNo:NULL<p/>";}
else {echo "<p>mobileTelNo : $mobileTelNo </p>";}
echo "<p>sendMethod : $sendMethod </p>";
?>
i need the term and condition check box to be checked else use cannot submit the form....
REMEMBER! Using javascript will just make it easy for user.It prevents loading another page to display error. STILL if a browser has javascript turned of it will pass the checked Terms without even checking it. so you should Always check it serverside (PHP) and use javascript for users ease.
in your HTML:
<form id="userdetail" ....>
...
<input type="checkbox" name="terms" id="terms" value="accepted" />
...
</form>
then in your javascript:
Pure JS:
document.getElementById('userdetail').addEventListener('submit', function(event){
if(document.getElementById('terms').checked == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
Using JQuery (jquery.com)
$('#userdetail').submit(function(event){
if($('#terms').is(':checked') == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
and in your PHP to check if it is checked you should use
if(isset($_POST['terms']) && $_POST['terms'] == 'accepted') {
// Continue Registring
} else {
// Display Error
}
Instead of submit you do:
<input type="button" onclick="javascript:myFunction()" Value="Submit">
And then the javascript function:
function myFunction() {
if(document.getElementById("terms").checked == true){
document.getElementById("userdetail").submit();
}
else{
alert("You have to agree on terms and conditions");
}
}
In Jquery you can do like below:
<script>
$('#userdetail').submit(function(){
if($('#terms').is(':checked'))
{
return true;
}
else
{
return false;
}
});
</script>
Replace the part of html with the given html in answer and add the function below to you script...
function verify_terms()
{
if (!$('#terms').is(':checked'))
{
alert('Please agree terms and conditions');
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" onclick="return verify_terms();" value="submit" />

How to disable submit till only required fields are filled up

I have searched but I get info about how to disable submit button till all fields are completed....
I have following form where some fields are required and some are optional.
I want to disable submit button till required fields are completed.
sample code of form :
<form name="registration_form" id="registration_form" action="nextaction.php" method="post" enctype="multipart/form-data" >
Name : <input type="text" id="name" name="name" required>
Email : <input type="text" id="name" name="name" required>
Mobile : <input type="text" id="mobile" name="mobile" required>
Gender : <input type="text" id="gender" name="gender" >/*optional*/
Occupation : <input type="text" id="occupation" name="occupation" >/*optional*/
City : <input type="text" id="city" name="city" required>
Avatar : <input type="file" id="avatar" name="avatar" required>
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" />
===========
Edited
what I have tried for submit disable untill all field completed as follows :
First Thing :
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" disabled="disabled" />
script :
<script>
$(document).ready(function (){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
});
</script>
$('#registration_form input[required]').on('input propertychange paste change', function() {
var empty = $('#registration_form').find('input[required]').filter(function() {
return this.value == '';
});
$('#register').prop('disabled', (empty.length));
});
https://jsfiddle.net/ot5kn5c7/
This should work.
Anytime anything changes on any required input check for the count of required fields that are not empty. Once there are 0 required empty inputs update the disabled property for the button. (0 evaluates as false)
If you didn't to disable the button and wanted to only stop the form from submitting you would attach to the submit event on the form and just prevent the default action using similar logic checking the length.
$('form').on('submit', function(e) {
var empty = $(this).find('input[required]').filter(function() {
return this.value == '';
});
if (empty.length) {
e.preventDefault();
alert('enter all required field!')
}
});
Working solution for your case: https://jsfiddle.net/j9r5ejho/
$('form').submit(function(){
var valid = true;
$('input[required]').each(function(i, el){
if(valid && $(el).val()=='' ) valid = false;
})
return valid;
})
Untested but it should work with something like this:
(function() {
// whenever you type in a field
$('form > input').keyup(function() {
var empty = false;
// scan all fields in this form with the attribute required
$('form').find('input[required]').each(function() {
// if it's empty, cancel the loop
if ($(this).val() == '') {
empty = true;
return false;
}
});
// in case we have an empty required field,
// disable submit button
if (empty) {
$('input:submit').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})();
In order to prevent posting the form on a button or input type="submit", you can simply use e.preventDefault() which would prevent from proceeding with the default behavior.If you are using jquery validation and have a required attribute, you can just invoke $.validate() to validate the form.
$('input:submit').click(function(e)
{
if(!$.validate())
e.preventDefault();
});
example : https://jsfiddle.net/DinoMyte/suj951ga/1/
Just in case you want to try something like this. This won't disable the submit button but if you want to stop it from submitting until all required fields are fill in. This should work.
Not sure what database your using but this is for the PDO. You can just change the connection part to mysqli.
It won't submit to your database until you complete all the required fields and will also display the required input error messages.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white
space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success! Form Submitted!";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Use this if you want to redirect it to another page so it won't send the form again to your PDO database if they refresh it.
It won't submit to your database and will stay on the HOME.PHP page until you complete all the required fields and will also display the required input error messages while on HOME.PHP page.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
Added a "header("Location: welcome.php");" after "$conn->exec($sql);"
HOME.PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
header("Location: welcome.php");
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
WELCOME.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Success! Form Submitted!</h1>
<script type="text/javascript" src="js/main.js" ></script>
</body>
</html>

Clear PHP Form after submission

O.k I have seen similar questions but can't seem to make it work. I would like that when the form is submitted the fields get cleared.
This is my PHP:
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "EMAIL ADDRESS";
$subject = "Unriddle contact form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo '<p style="margin-top: 1em; font-color: #66CC00;">Thank you!</p>'; ?>
This my HTML:
<form action="mail.php" method="post">
<a class="form-row">
<p>Name</p>
<input id="iname" type="text" class="text-input required default" name="name" value="" />
</a>
<a class="form-row">
<p>Email</p>
<input id="email" type="text" class="text-input required email default" name="email" value="" />
</a>
<a class="form-row">
<p>Message</p>
<textarea id="message" class="text-area" name="message" cols="40" rows="8"></textarea>
</a>
<br />
<input class="btn-submit" type="submit" value="Send" name="submit" />
This is my JS
jQuery(document).ready(function($) {
var $loading = $('<div class="loading"><img src="/js/loading.gif" alt="" /></div>');
$(".default").each(function(){
var defaultVal = $(this).attr('title');
$(this).focus(function(){
if ($(this).val() == defaultVal){
$(this).removeClass('active').val('');
}
});
$(this).blur(function() {
if ($(this).val() == ''){
$(this).addClass('active').val(defaultVal);
}
})
.blur().addClass('active');
});
$('.btn-submit').click(function(e){
var $formId = $(this).parents('form');
var formAction = $formId.attr('action');
defaulttextRemove();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
$('li',$formId).removeClass('error');
$('span.error').remove();
$('.required',$formId).each(function(){
var inputVal = $(this).val();
var $parentTag = $(this).parent();
if(inputVal == ''){
$parentTag.addClass('error').append('<span class="error">Required field</span>');
}
if($(this).hasClass('email') == true){
if(!emailReg.test(inputVal)){
$parentTag.addClass('error').append('<span class="error">Enter a valid email address</span>');
}
}
});
if ($('span.error').length == "0") {
$formId.append($loading.clone());
$('fieldset',$formId).hide();
$.post(formAction, $formId.serialize(),function(data){
$('.loading').remove();
$formId.append(data).fadeIn();
});
}
e.preventDefault();
});
});
function defaulttextRemove(){
$('.default').each(function(){
var defaultVal = $(this).attr('title');
if ($(this).val() == defaultVal){
$(this).val('');
}
});
}
Is there a simple way of doing this ? What line of code do I need to add and where ? If you can help me that would be great, but please be specific as to where I should add the line of code.
Power to you! Thanks
Add reset on success of your ajax request or if you want to clear every time on submit add at the end .
if ($('span.error').length == "0") {
$formId.append($loading.clone());
$('fieldset',$formId).hide();
$.post(formAction, $formId.serialize(),function(data){
$('.loading').remove();
$formId.append(data).fadeIn();
$formId.reset();// to reset
});
}

How configured contact form for sending email

I request your kind help with this problem. I have a website with the respective contact form, but it has never worked for me. The messages do not arrive. Sending them the contact page send_mail.php file and everything related. I thank you very much the help and detailed explanation as this topic is very complex.
Contact.js
$(document).ready(function(){
$('#send_message').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut.
The only difference from these checks is the email checking, we have
email.indexOf('#') which checks if there is # in the email input field.
This javascript function will return -1 if no occurence have been found.*/
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
}else{
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("send_email.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#button').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#send_message').removeAttr('disabled').attr('value', 'Submit');
}
});
}
});
});
Send_mail.php
require_once 'google/appengine/api/mail/Message.php';
use google\appengine\api\mail\Message;
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$message_body = "...";
$mail_options =[;
"sender" => "administrador#formarchivos.com",
"to" => $email,
"subject" => $subject,
"textBody" => $message_body
];
try {
$message = new Message($mail_options);
$message->send();
echo 'sent';
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
echo 'failed';
}
Contact.html
<!-- Contact Form -->
<form action="send_email.php" method="post" id="contact_form">
<h3>Ficha de contacto</h3>
<div class="hr dotted clearfix">
<h3> </h3>
</div>
<ul>
<li class="clearfix">
<h3>
<label for="name">Nombre</label>
<input type='text' name='name' id='name' />
</h3>
<div class="clear"></div>
<h3 id='name_error' class='error'>Inserte un nombre</h3>
</li>
<li class="clearfix">
<h3>
<label for="email">Email </label>
<input type='text' name='email' id='email' />
</h3>
<div class="clear"></div>
<h3 id='email_error' class='error'>Ingrese una cuenta de correo valida</h3>
</li>
<li class="clearfix">
<h3>
<label for="subject">Tema</label>
<input type='text' name='subject' id='subject' />
</h3>
<div class="clear"></div>
<h3 id='subject_error' class='error'>Ingrese un Tema para su mensaje</h3>
</li>
<li class="clearfix">
<h3>
<label for="message">Mensaje</label>
<textarea name='message' id='message' rows="30" cols="30"></textarea>
</h3>
<div class="clear"></div>
<h3 id='message_error' class='error'>Ingrese su mensaje</h3>
</li>
<li class="clearfix">
<h3 id='mail_success' class='success'>Gracias. Nosotros te responderemos tan pronto como nos sea posible.</h3>
<h3 id='mail_fail' class='error'>Disculpenos, un error ha ocurrido. Por favor intentelo despues.</h3>
<div id="button">
<h3>
<input type='submit' id='send_message' class="button" value='Enviar' />
</h3>
</div>
<!--end wrapper-->
<div align=center></div></body>
</html>
This is all that I have, I have nothing mensaje.php, if I may not need any extra file to be honest I do not know where can be the error.
Aside from your syntax error suggested by #koljanep I have a couple suggestions/comments:
Have you tried doing a function (perhaps even on the php page) to handle your
jQuery errors instead of repeating a bunch of same fade effects?
Maybe sanitize your inputs on the PHP page.
Perhaps a more straight-forward AJAX would help.
You assign
$message = $_POST['message']; but then you assign $message = new
Message($mail_options); so there is some weirdness going on
there...
Contact.js
$(document).ready(function(){
$('#contact_form').submit(function(e){
$.ajax({
url:"Send_mail.php",
type: 'POST',
data: $("#send_message").serialize(),
success: function(data) {
// This id would have to be somewhere on your page
// to drop into (I'm sure you know that)
$("#response").html(data);
}
});
return false;
});
});
Send_mail.php
<?php
// Do some basic sanitizing...I chose preg_replace, but you can do whatever
$setting['name'] = (!empty($_POST['name']))? preg_replace('/[^0-9a-zA-Z\.\']/'," ",$_POST['name']):0;
$setting['subject'] = (!empty($_POST['subject']))? preg_replace('/[^0-9a-zA-Z\.\']/'," ",$_POST['subject']):0;
$setting['message'] = (!empty($_POST['message']))? strip_tags($_POST['message']):0;
// Check first that the email is a valid one!
if(isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// If all checks out,
if(!in_array(0,$setting)) {
require_once('google/appengine/api/mail/Message.php');
use google\appengine\api\mail\Message;
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$message_body = "...";
$mail_options = [
"sender" => "administrador#formarchivos.com",
"to" => $email,
"subject" => $subject,
"textBody" => $message.$message_body
];
try {
$sendMessage = new Message($mail_options);
$sendMessage->send();
echo 'sent';
}
catch (InvalidArgumentException $e) {
echo $e->getMessage();
echo 'failed';
}
}
else
$_error = $setting;
}
else {
$setting['email'] = 0;
$_error = $setting;
} ?>
<script>
function ReturnError(IdVal) {
$('#'+IdVal+"_error").fadeIn(500);
}
<?php
if(isset($_error)) {
foreach($_error as $key => $errored) {
if($errored == 0) { ?>
ReturnError('<?php echo $key; ?>');
<?php }
}
} ?>
</script>

Categories