I made a website using css, html, javascript and a little php. I have it hosted on a hosting site with a domain name, but I'm having issue with the server side validation for the form.
It's just a simple contact form:
First Name
Last Name
Email
Message (textarea)
Submit button
I have javascript validation and it works fine. The form won't submit at all unless the correct amount of characters are input, but obviously that's useless if the user has js disabled. I've also finally gotten the form to email to my personal email using php... But obviously I need server side validation as well.
Today was my first day really getting into php and I was hoping to have the php validation done by today, but of all the videos I watched, I just came away more confused. All I want to do is just make it so that if the user has javascript disabled for whatever reason, or if he leaves the fields blank, the form won't submit...
Anyeay, I was working on this all day today with the intention of getting the form to send to my email, I finally accomplished that. Then realized I had no server side validation. I spent a few hours researching it and attempting it to no avail. Can anyone here just give me the php validation code for the kind of form I described above? It's for my business website so the sooner I can have a working contact form on it, the better...
Here is the html contact form I made.
<form action="message_sent.php" method="POST" onSubmit="return validateTextbox();">
<p class="message">
<div class="row">
<label for="firstname"><!--First Name (Required):--> </label>
<input type="text" id="firstname" name="first_name" size="40" placeholder="First Name (Required)"></br> </br> </div>
<div class="row">
<label for="lastname"><!--Last Name (Required):--> </label>
<input type="text" id="lastname" name="last_name" size="40" placeholder="Last Name (Required)"/> </br> </br></div>
<div class="row">
<label for="email"><!--Your Email (Required):--></label>
<input type="email" id="email" name="email" size="40" placeholder="Email (Required)"/> </br> </br></div>
<!--<p class="yourMessage">Your Message (10 Character Minimum):</p>-->
<textarea id="theform" rows="30" cols="80" name="message" placeholder="Your Message (10 Character Minimum):"></textarea></br>
</p>
<input type="submit" name="submit" onclick="return val();" value="SUBMIT">
</form>
</body>
</html>
Here is the javascript validation:
/*============================ CONTACT US PAGE ==========================*/
function validateTextbox() {
var box = document.getElementById("firstname");
var box2 = document.getElementById("lastname");
var box3 = document.getElementById("email");
var box4 = document.getElementById("theForm");
if (box.value.length < 1 || box2.value.length < 1 || box3.value.length < 5){
alert("You must enter a value");
box.focus();
box.style.border = "solid 3px red";
box2.focus();
box2.style.border = "solid 3px red";
box3.focus();
box3.style.border = "solid 3px red";
return false;
}
}
function val(){
if(document.getElementById("theform").value.length < 10
&& document.getElementById("theform").value.length > 0){
alert("You must enter at least 50 characters. Tell us what you need so we can better assist you.");
return false;
}
else if(document.getElementById("theform").value.length === 0){
alert("You cannot submit an empty form.");
theform.focus();
theform.style.border = "solid 3px red";
return false;
}
}
/*function val(){
if(document.getElementById("theform").value==null || document.getElementById("theform").value==""){
alert("The Message field cannot be blank.");
return false;
}
*/
/*
*/
/*=======================|| box4.value.length < 70) ================================================ */
/*========= CONTACT PAGE========================================*/
/*
function contactPage(){
alert("This Contact Form is NOT OPERATIONAL.");
Here is the php submission success page... the code I used to have the form send to my email:
<?php
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$message=$_POST['message'];
$to="default#email.com";
$subject="A visitor has sent you a new message";
$body="You have received a message from: \n\n
First Name: $first_name\n
Last Name: $last_name\n
Email: $email\n\n
MESSAGE: $message";
mail($to, $subject, $body);
print "<p>Message Sent! <a href='index.html'>Click. here</a> to return to the homepage</p>"
?>
Simple and complete example:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//Define variable as empty to avoid "undefined variable error".
$FnameErr = $LnameErr = $emailErr = ""; //Each variable contain error string of specific field.
$fname = $lname = $email = $message = ""; //Main inputed data of specific field
if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if request is posted.
//First name check
if (empty($_POST["fname"])) { // check if empty then assign a error string in spacific variable
$FnameErr = "First Name is required";
}else{ // if not empty then store as right data
$fname = filter_data($_POST["fname"]); //filter with unexpected special char and trim.
}
//Last name
if (empty($_POST["lname"])) { // check if empty then assign a error string in spacific variable
$LnameErr = "Last Name is required";
}else{ // if not empty then store as right data
$lname = filter_data($_POST["lname"]); //filter with unexpected special char and trim.
}
//email
if (empty($_POST["email"])) { // check if empty then assign a error string in spacific variable
$emailErr = "Email is required";
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // validate email with php build-in fucntion.
$emailErr = "Invalid email format";
}else{ // if not empty and valide email then store as right data
$email = filter_data($_POST["email"]); //filter with unexpected special char and trim.
}
}
//message with no validation
if (empty($_POST["message"])) {
$message = "";
} else {
$message = filter_data($_POST["message"]);
}
//Database query
if($FnameErr =="" && $LnameErr =="" && $emailErr==""){
//MYSQL insert statement that you know
// $sql = "INSERT INTO tablename .................."; values = $fname; $lname; $email; $message;
}
}
// A function to trim data and remove special charecter
function filter_data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name: <input type="text" name="fname" value="">
<span class="error">* <?php echo $FnameErr;?></span><br><br>
Last Name: <input type="text" name="lname" value="">
<span class="error">* <?php echo $LnameErr;?></span><br><br>
E-mail: <input type="text" name="email" value="">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Message: <textarea name="message" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $fname;
echo "<br>";
echo $lname;
echo "<br>";
echo $email;
echo "<br>";
echo $message;
?>
</body>
</html>
This is just a basic empty check validation.
Validations in PHP are not very difficult.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(trim($_POST['firstname']) === ''){
echo 'Please enter firstname';
}
}
You can also learn some validations here
http://www.w3schools.com/php/php_form_validation.asp
Related
I am doing this to learn, got it from examples here and there and, following an online tutorial. What I have not been able to do so far is to prevent it to go to the confirmation.php page if one of the entry is either empty, has numbers (name and lastname) or the email adress is invalid.
If i use action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" I see when thre is an error in the fields but, when action is set to confirmation.php, even if there is an error, it will go with the entered data.
Just for info of my next step, confirmation.php would be a page displaying the info entered with a submit button (to a DB) or an update button if the user made a mistake so he can fix it before sending to db.
Just so you know, I am just starting paying with php so, please, I would appreciate if your answer was not to generic :-)
Thank you
<?php
// define variables and set to empty values
$nameErr = $lastNameErr = $emailErr = "";
$name = $lastName = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])||(ctype_space($_POST["name"]))) {
$nameErr = "Prénom Requis";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Lettre seulement";
}
}
if (empty($_POST["lastName"])||(ctype_space($_POST["lastName"]))) {
$lastNameErr = "Nom Requis";
} else {
$lastName = test_input($_POST["lastName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
$lastNameErr = "Lettre seulement";
}
}
if (empty($_POST["email"])||(ctype_space($_POST["email"]))) {
$emailErr = "Adresse courriel requise";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Adresse courriel non valide";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Inscription du participant</h2>
<p><span class="error">* Champ requis.</span></p>
<form method="post" "confirmation.php">
Prénom: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Nom: <input type="text" name="lastName" value="<?php echo $lastName;?>">
<span class="error">* <?php echo $lastNameErr;?></span>
<br><br>
Courriel: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You can easily achieve what you want just by adding the "required" attribute to your input field html element.
Have a look here: https://www.w3schools.com/tags/att_input_required.asp
By adding "required" the browser itself will prevent the form to be sent.
Furthermore, for the "email" input, try to change its type to email (type="email" which will also add the default browser validation for an email address.
Have a look here for more default validation in form input fields: https://www.w3schools.com/htmL/html_form_input_types.asp
You are missing action= inside your <form>. It just says confirmation.php
I am currently trying to make a HTML form page [main.html], which will take following input :
Name, Email, and Contact Number
when the data is submitted, it will go to PHP script [validate.php] where it will be validated. like whether the name contains any invalid character set or number etc.
if the validation fails, it should return error msg e.g "Data Validation Fails".
and if the validation is successful, PHP page should return the data to main.html where the received data needs to be displayed and user is asked to confirm it again.
Once the data is confirmed by the User, it will be send data to another PHP Script file [store.php] for storing in a text file [e.g. UserDb.txt].
I am very much new to PHP and HTML with no knowledge of JQuery. I can somehow prepare main.html and store.php but heavily confused for validate.php page.
Please tell me how can i send back the data from PHP page [validate.php] to HTML page [main.html] to ask for confimation ??
Please do not suggest solutions involving JQuery and AJAX.
There are lot of webpages for that which I can find on Internet, but i could not find any solution particularly for this case. I Hope it is possible to send data back to HTML Page from PHP Script.
Form action tag is there for that action. Lets see on an example. here we have our form main_form.php;
<form action="validation.php" method="post">
<h2>Form</h2>
<span class="error">* required field.</span>
Name:
<input name="name" type="text" value="">
<span class="error">* <?php echo $nameError;?></span>
E-mail:
<input name="email" type="text" value="">
<span class="error">* <?php echo $emailError;?></span>
Gender:
<input name="gender" type="radio" value="female">Female
<input name="gender" type="radio" value="male">Male
<span class="error">*<?php echo $genderError;?></span>
Website:
<input name="website" type="text" value="">
<span class="error"><?php echo $websiteError;?></span>
Comment:
<textarea cols="40" name="comment" rows="5">
</textarea>
<input name="submit" type="submit" value="Submit">
</form>
Now lets see how we validate on validation.php;
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$websiteError ="";
// On submitting form below function will execute.
if(isset($_POST['submit'])){
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailError = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check address syntax is valid or not(this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteError = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderError = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//php code ends here
?>
If there is an error this script will return error to the our main_form.php.For errors use css to show them in red like below error.css;
.error{
color:red
}
TL;DR: Set form action to validation.php. Keep it simple.
To start and set a session variabl :
session_start(); //at top of page
$_SESSION['name_of_field'] = $_POST['name_of_field']; //do checks on the post data!
To use a session varible :
session_start(); //at top of page
$my_new_value = $_SESSION['name_of_field'];
you will get data in varible.
Or you can send data via URL
Write this in php
header('Location: http://yoursite.com/page2.php?name='.$name.'&email='.$email);
and get
$name = $_GET['name'];
$email = $_GET['email'];
You may also try
Rename your main.html to main.php then include validate.php above your form tag to display errors above form. Thus, your form action would be self or blank
<?php include "validate.php"; ?>
<form action ="" method ="post"... >
But if there are no errors, then from validate.php you can redirect to the index.php for user confirmation using
header('Location: index.php?name='.$name);
The value of name can be accessed using $_GET['name'];
In this program when i am clicking submit button the page directly goes on other page 2222.php. The error message not pop up.. I just want hit error message when clicking on submit button...
php_validation.php
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$name = $email = $gender ="";
// On submitting form below function will execute.
if(isset($_POST['submit']))
{
if (empty($_POST["name"])) //---------------------------------------------- -------------------------
{
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
//-----------------------------------------------------------------------
}
if (empty($_POST["email"])) //---------------------------------------------- -------------------------
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format";
}
}
//-----------------------------------------------------------------------
if (empty($_POST["gender"]))
{
$genderError = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" name="myForm" action="2222.php">
<p>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError;?></span>
</p>
<br><br>
<p>
Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError;?></span>
</p>
<br><br>
<p>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">*<?php echo $genderError;?></span><br><br />
</p>
<input class="submit" type="submit" name="submit" value="Submit" >
</form>
</body>
2222.php
<?php
$name = $_POST['fname'];
$email = $_POST['email'];
$radio = $_POST['gender'];
echo "<h2>Your Input:</h2>";
echo "user name is: ".$name;
echo "<br>";
echo "user email is: ".$email;
echo "<br>";
echo "user is ".$radio;
?>
So I've done a quick code for you :
Here is your "php_validation.php" :
<?php
//Init error var
$nameError = '';
$emailError = '';
$genderError = '';
//Did we have an error ?
if(isset($_GET['error'])){
//Split error return into an array
$errorList = explode('_', $_GET['error']);
//Verify every possible error
if(in_array('name',$errorList)){
$nameError = 'Please enter your name<br>';
}
if(in_array('email',$errorList)){
$emailError = 'Please enter your email<br>';
}
if(in_array('gender',$errorList)){
$genderError = 'Please enter your gender';
}
}
?>
I didnt changed the form
Then this is your "2222.php" :
<?php
$error ='';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//When we receive data
if(isset($_POST)){
//Verify all possible data and set error
if(!empty($_POST['fname'])){
$name = test_input($_POST['fname']);
}else{
$error .= 'name_';
}
if(!empty($_POST['email'])){
$email = test_input($_POST['email']);
}else{
$error .= 'email_';
}
if(!empty($_POST['gender'])){
$radio = test_input($_POST['gender']);
}else{
$error .= 'gender_';
}
//if we have an error then redirect to form with error
if(!empty($error)){
header("Location:php_validation.php?error=".$error);
}
}
?>
Didnt changed your output on this page either.
So as I said previously when you here is what happend when you click the submit button :
Submit Click
Form sent to 2222.php as $_POST and you're redirected to this page
There is no way that could be working if your form is posting on an other page than the one where the check is made.
Since your form's action is "2222.php", on click the submit button will automatically redirect you to 2222.php before doing anything.
If you want to check what you've received by your form, you can do it in your "2222.php", then redirect it with the error message to php_validation.php
You could do one of the following things:
Do all the checking in Javascript "onClick" function
Do Ajax call "onClick" to a handler page, get the validation message from that page.
Do the validation on "2222.php" page
action back to the same page (since you are doing some validation here) and redirect after validation on "2222.php" page
Now depends only on you which fits your program.
If you want to stay on the same page you could submit the form to an iframe, as the results of the processing script would be displayed in the iframe itself.
Example:
files:
file-with-form.php
form-submit-processing-file.php
Code examples:
file-with-form.php
<!DOCTYPE html>
<html>
<head>
<title>[Your page title]</title>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<!-- Form -->
<form action="[path-to-form-submit-process]" method="[GET|POST]"
target="form-processor">
<div>
<label>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError ?></span>
</label>
</div>
<div>
<label>Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError ?></span>
</label>
</div>
<div>
<label>Gender:
<p><input type="radio" name="gender" value="female"> Female</p>
<p><input type="radio" name="gender" value="male"> Male</p>
<p><span class="error">*<?php echo $genderError ?></span></p>
</label>
<input class="submit" type="submit" name="submit" value="Submit" >
</div>
</form>
<!-- The iframe to submit the form to -->
<iframe name="form-processor" id="form-processor"
src="[path-to-form-submit-process]"></iframe>
<!--
NOTE: The error message spans are left there just because you had them
in your code, those will not work here at this point, actually depending
on your php configuration will most probably throw errors/warnings,
because such variables were not defined at all...
-->
</body>
</html>
As:
[path-to-form-submit-process] - a placeholder to be replaced with the URL to the file/ Controller -> Action that would process the passed form data
[*] - placeholders that should be replaced with the values for your case
form-submit-processing-file.php
<?php
# Processing the form fields and displaying the messages
$post = $_POST;
# Preprocessing the passed data
// Here you would filter out data from the $_POST superglobal variable
# Validating the passed data
// Check if the data entries, e.g.
// Flag for error risen - does not let the process to be completed
$invalidFormData = false;
$messages = [];
function addErrorMessage($message, &$messages, &$errorFlag)
{
$errorFlag = true;
$errorMessageTemplate = '<p class="error-message">{message}</p>';
array_push($messages, str_replace('{message}', $message,
$errorMessageTemplate));
}
// Validating the email
$email = array_key_exists('email', $post)
? $post['email']
: null;
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
// Raising the flag for an error on validation
addErrorMessage("$email is not a valid email address", $messages, $invalidFormData);
}
// ........
// validation of rest of fields
// ........
$internalError = false;
# Some business logic after the validation, recording more messages etc.
try {
// ........
} catch (Exception $e) {
$internalError = true;
}
# Stop execution on internal error
if ($internalError === true)
{
?>
<h2>Sorry, there's an error on our side... we'll do all in our
powers to fix it right away!</h2>
<?php
exit;
}
# Displaying the results
if ($invalidFormData === true) {
// Building errors message
$messagesHeading = '<h2>There were problems submitting your data. :/</h2>';
} else {
$messagesHeading = '<h2>Your data was successfully submitted! Yay!</h2>';
}
// Placing the heading in front of other messages
array_unshift($messages, $messagesHeading);
// Displaying the messages:
echo implode('', $messages);
However I believe this should be done via an AJAX call insted.
Also there are a lot of bad practices in this case, so I would suggest checking out some design patterns and architectures as MVC for instance and consider using a framework like Symfony/Laravel/CodeIgniter... There are a lot of tools that will make your life easier :)
Good Afternoon Everyone. I have a pretty unique situation which I cannot seem to find the answer for. I have a form which send to an email, but once the form is submitted it redirects to the php file which processes the information and sends the email. I've searched everywhere and seen that what I am trying to accomplish can be done using AJax, but I cannot seem to get it to work. I have my for load into a div which is contained on my index.html using JQuery. The problem is that when I submit it redirects to the php file, but I want it to remain inside the index.html containing it. I have placed my codes below. Thank you in advance.
<form name="inquiryForm" id="inquiryForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
method="POST">
<fieldset>
<legend>* Required</legend>
<br>
First Name<input type="text" name="fname" value="<?php echo $fname;?>">
<span class="error">* <?php echo $fnameErr;?></span><br><br>
Last Name<input type="text" name="lname" value="<?php echo $lname;?>">
<span class="error">* <?php echo $lnameErr;?></span><br><br>
Phone Number<input type="text" name="phone" value="<?php echo $phone;?>"><br><br>
Email Address<input type="text" name="email" value="<?php echo $email;?>">
<span class="error"><?php echo $emailErr;?></span><br><br>
<label>How did you find us?</label>
<select name="how">
<option value=""> -- Please select -- </option>
<option>Google</option>
<option>Yahoo</option>
<option>Link from a website</option>
<option>Word of mouth</option>
<option>Other</option>
</select><br><br>
<label>Inquiry*</label><br>
<textarea name="inquiry" value="<?php echo $inquiry;?>" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $inquiryErr;?></span><br><br><br>
<input type="submit" name="submit" id="submit" value="Submit">
<input type="reset" name="reset" value="Reset">
</fieldset>
</form>
Below is my php file
<?php
/* Set e-mail recipient */
$myemail = "my email address";
$subject = "Ism Clothing Contact Form Submission";
// define variables and set to empty values
$fnameErr = $lnameErr = $emailErr = $inquiryErr = "";
$fname = $lname = $email = $inquiry = "";
$phone = $_POST['phone'];
$how = $_POST['how'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "First Name is required";
} else if (empty($_POST["lname"])) {
$lnameErr = "Last Name is required";
} else {
$fname = test_input($_POST["fname"]);
$lname = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
} else if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["inquiry"])) {
$inquiryErr = "Please enter questions comments, or concerns";
} else {
$comment = test_input($_POST["inquiry"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
/* Format form data for email */
$message = "Hello!
Ism Clothing contact form has been submitted by:
Name: $fname $lname
E-mail: $email
Phone #: $phone
How did he/she find it? $how
Comments:
$inquiry
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
?>
and below is the Jquery code which loads my contact.php (form) into my main page (index.html)
$("#contact").on("click", function(){
$("#content").load("contact.php");
});
I am using that code above in my index.js to load contact.php into a div in my index.html.
Try this out :
$("#inquiryForm").on("submit", function(e){
e.preventDefault();
$this = $(this);
$.ajax({
type: "POST",
url: $this.attr('action'),
data: $this.serialize(),
success : function(){
alert('Done');
}
});
});
You've got a bit of confusion.
Using Ajax you don't need a form at all: you show input fields to the user, then at a button press you build an Ajax request and wait for a reply. This mean that your page do not move from where it stands.
Instead, when submitting a form, HTML expects a place where to output the form results: by submitting you are navigating to an url, after all.
Now, you have two solutions:
1) learn how to use Ajax.
2) put an hidden iFrame on the page, give it an ID, set the form target to that ID and add an handler to the iFrame loaded event
I have a form with an action that is linked to the same PHP page contact.php. I have all the server side validation inside the form and it's all fine. It redirects the user to the same page with error messages echoed if needed while making the form STICKY (that is the main point of using the same page for errors).
What I would like is for there to be a success page redirect if the form was okay. I've read other posts on how to implement this, but I don't quite understand how to implement it in my code.
<?php
$fullname = $email = $reason = $contactbox = '';
$fullnameerr = $emailerr = $reasonerr = $contactboxerr = '';
if(data_post('submit')){
if(empty(data_post('firstname'))){
$fullnameerr = "Please enter a valid name";
}
else {
$fullname = clean_data(data_post('firstname'));
if (!preg_match("/^[a-zA-Z '']*$/", $fullname)){
$fullnameerr = "Please enter only alphabetical characters and white spaces";
}
}
if(empty(data_post('email'))){
$emailerr = "Please enter a valid e-mail";
}
else {
$email = clean_data(data_post('email'));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailerr = "Please enter a correct e-mail format (ex 'joe#cornell.edu')";
}
}
if(empty(data_post('reason'))){
$reasonerr = "Please select a reason for contact";
}
else{
$reason = clean_data(data_post('reason'));
}
if(empty(data_post('contacttext'))){
$contactboxerr = "Please elaborate on your reason";
}
else{
$contactbox = clean_data(data_post('contacttext'));
if(!preg_match("/^[\w\S\s]*$/", $contactbox )){
$contactboxerr = "Please enter only valid characters you would use in writing (ex 'abcABC123')";
}
if(strlen($contactbox) > 2000){
$contactboxerr = "Please enter a response with with a max of 2000 characters.";
}
}
}
function clean_data($field){
$field = trim($field);
$field = stripslashes($field);
return $field;
}
function data_post($param){
if (isset($_POST[$param])){
return $_POST[$param];
}
else{
return '';
}
}
?>
With this being the code for the form:
<div class="sidesection" id="survey">
<h3>Contact Form</h3>
<form action="contact.php" method="POST" novalidate>
<span class="required_asterick">* Is Required</span>
<fieldset>
<legend>Contact Us</legend>
<span class="required_asterick">* </span><label>Name:</label><span class="help" data-tooltip="Please enter a valid name (Ex. 'John Doe')"></span><br />
<input type="text" name="firstname" required pattern="[a-zA-Z '']+" maxlength="25" title="Enter only characters from (a-z) and (A-Z)" value="<?php echo "$fullname";?>"><span class="errormessage"><?php echo "$fullnameerr";?></span><br /><br />
<span class="required_asterick">* </span><label>Email:</label><span class="help" data-tooltip="Please enter a valid email with a max of 50 characters. (Ex. 'xxx#yyy.com')"></span><br />
<input type="email" name="email" required maxlength="50" value="<?php echo "$email";?>">
<span class="errormessage"><?php echo "$emailerr"; ?></span><br /><br />
<span class="required_asterick">* </span><label>Reason For Contact:</label>
<select name="reason" required>
<option value=""> </option>
<option value="general">General</option>
<option value="concern">Concern</option>
<option value="feedback">Feedback</option>
</select><span class="help" data-tooltip="Choose a topic for which you are contacting us so we can process your request faster. General is for any broad topics not listed. Concern is for any pressing matter you may have about the Ithaca Apple Harvest Festival. Feedback is for any suggestions or opinions you wish to share with us about our festivals. "></span><span class="errormessage"><?php echo "$reasonerr";?></span><br /> <br />
<span class="required_asterick">* </span><label>What Would You Like To Tell Us?</label><span class="help" data-tooltip="Use this section to write what you are contacting us for."></span><br />
<textarea name="contacttext" rows="7" cols="60" required><?php echo "$contactbox";?></textarea><span class="errormessage"><?php echo "$contactboxerr"; ?></span><br />
<input type="submit" value="Submit" name="submit">
</fieldset>
</form>
You can see I made the form sticky by adding echoes to errors, so I want to keep that if there are errors. However if it is successful, redirect to a success page.
Just check if you have no errors (i.e. your error variables are empty) and use header()
$fullname = $email = $reason = $contactbox = '';
$fullnameerr = $emailerr = $reasonerr = $contactboxerr = '';
if(data_post('submit')){
// your validations go here
// ......
if (empty($fullnameerr) && empty($emailerr) && empty($reasonerr) && empty($contactboxerr)) {
header('Location: success.php');
}
}
You don't have a control to check whether the validation passed or failed. As a suggestion user a boolean variable to indicate it:
if(data_post('submit')){
$valid=true;
if(empty(data_post('firstname'))){
$fullnameerr = "Please enter a valid name";
$valid=false;
}
if(empty(data_post('email'))){
$emailerr = "Please enter a valid e-mail";
$valid=false;
}
//other validations
if($valid){
//validation passed
header('Location: destination.php');
}
}
In addition to #Deimoks answer, you may need to call exit(); after calling the header() function. If you have any code after the header redirection, it could still be executed even you requested a redirection. exit() prevents that. Also, if you get the "headers already sent" error, look into output buffering.