Validating form and sending a confirmation email on submission - php

I am creating an admin page, where the admin person can create users accounts for people. The idea is, that once the form is completed, when clicking 'Submit' an email must be sent to the user (containing the ID and name of account selected). In the same action, the form must also first be validated and if there are any errors with the validation the data should not be submitted to the database. None of this is happening though and I cannot figure out why.
The email is not being sent,
the data is inserted in the database even if there are errors and upon loading the page,
errors are displayed for all form fields even though the submit button have not been clicked.
Any help, advice or links to possible sources/tutorials would be greatly appreciated.
Below is my code: (Note that I am only working in PHP, HTML and using a MYSQL database)
<html>
<head>
<title>
User Registration
</title>
<?PHP
include_once 'includes\functions.php';
connect();
error_reporting(E_ERROR | E_PARSE);
//Assign variables
$accounttype=mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
//Validating form(part1)
$error='';
//Connect to database
$SQL=
"INSERT INTO student
(
sname,fname,email, address, contact_flag
)
VALUES
(
'$sname', '$fname', '$email', '$address', '$contact_flag'
)
";
if (!mysql_query($SQL))
{
print'Error: '.mysql_error();
}
mysql_close($db_handle);
//Validate form(part 2)
if (isset($_POST['sname'], $_POST['fname'],$_POST['email'],$_POST['address']));
{
$errors=array();
$accounttype= mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
// form validation
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)===FALSE)
{
$errors[]='Please insert your valid email address';
}
if(strlen(mysql_real_escape_string($address))<8)
{
$errors[]='Please insert your postal address';
}
echo'<pre>';
print_r($errors);
echo'</pre>';
}
//confirmation email
// Subject of confirmation email.
$conf_subject = 'Registration confirmed';
// Who should the confirmation email be from?
$conf_sender = 'PHP Project <my#email.com>';
$msg = $_POST['fname'] . ",\n\nThank you for registering. \n\n You registered for account:".$accounttype."\n\n Your account number:".mysql_insert_id;
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
?>
</head>
<body>
</br>
<form name ="form0" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<b>Select the course you wish to register for:</b></br>
<select name="accounttype">
<?PHP query() ?>
</select>
<?PHP close() ?>
</form>
<form name ="form1" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<Input type ="" Value = "Surname" Name = "sname"></br>
<Input type ="" Value = "First name" Name = "fname"></br>
<b>Email:</b> <Input type ="" Value = "" Name = "email"></br>
<b>Address:</b> </br>
<textarea rows="4" cols="20" Name="address">Please provide your postal address here </textarea></br>
<b>Tick to receive confinmation email:</b> <Input type ="checkbox" Value = "1" Name = "contact_flag"></br>
<Input type = "Submit" Value="Submit">
</form>
</body>
</html>

<?PHP
if(isset($_POST['submit']))
{
include_once 'includes\functions.php';
connect();
// your rest of the code
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
}
?>
and keep this code out of the <html> tag but before it

and if you want to stick to PHP only then one error i can see is
that you have kept the **validation code below the `INSERT`**
query which means that the insert query will be executed first which will store the data in the database first and then it will go for the validation...so keep your validation code above the INSERT statement..
and second thing use exit() method after vaidating every field if it gives you error...it will stop executing rest of the php code if any field gives the error during validation....and so it will also prevent the data from storing into the database if it finds exit method whenever an error is found eg
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
echo '//whatever you want to echo';
exit();
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
echo '//whatever you want to echo';
exit();
}

At first, your query gets executed before you validate your form.
Move your SQL after your
echo'<pre>';
print_r($errors);
echo'</pre>';
and surround it with
if(!$errors){}
This will prevent your query from being executed if there are any errors.
(You can also delete your first assignement of your variables)
Concerning your email problem, test your connection with a simple message
mail('your#email.com', 'subject', 'message');
If you get any error, probably your mailserver isn't set up right

Related

Blank form keeps submitting (HTML, PHP)

So I have a contact form where customers can fill in their details. When submitted, the form posts the information across to a PHP script that then formats it into html and emails it to my business email.
The only problem I have is that I keep receiving blank emails at random. Obviously the PHP script is being triggered and an email is being sent but I'm not sure why.
The form has required fields so even if someone tried to submit it blank, it wouldnt let them. When I recieve these emails, there should at least be something in them.
I've thought about adding some extra validation to the PHP script to check if any of the required values are empty/missing, but the form deals with this anyway.
Does anyone know what is happening? It's probably something simple i've overlooked.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$budget = $_POST['budget'];
$timeframe = $_POST['timeframe'];
$desc = $_POST['desc'];
//Send HTML formatted email
$send = mail("nathan#nathanthompson.co.uk",
"You have received an enquiry",
"<html>
<body>
<h3>Here is the information for the enquiry: </h3>
<br>
<p>Name: $name</p>
<p>Email: $email</p>
<p>Budget: $budget</p>
<p>Timeframe: $timeframe</p>
<br>
<p>Description of enquiry:</p>
<p>$desc</p>
</body>
</html>
", "Content-type: text/html; charset=iso-8859-1");
if ($send)
{
header("Location:index.html");
}
else
{
echo "An error occurred. Please return to the contact form and try again.";
}
?>
Here you go, try this! :)
<?php
//Check the request method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Start by importing and sanitizing the fields
$name = sanitize($_POST["name"]);
$email = sanitize($_POST["email"]);
$budget = sanitize($_POST["budget"]);
$timeframe = sanitize($_POST["timeframe"]);
$desc = sanitize($_POST["desc"]);
//Make sure the fields are populated
if (empty($name)) {die("The 'Name' field was not populated. Please return to the contact form and try again.");}
if (empty($email)) {die("The 'Email' field was not populated. Please return to the contact form and try again.");}
if (empty($budget)) {die("The 'Budget' field was not populated. Please return to the contact form and try again.");}
if (empty($timeframe)) {die("The 'Time Frame' field was not populated. Please return to the contact form and try again.");}
if (empty($desc)) {die("The 'Description' field was not populated. Please return to the contact form and try again.");}
//Everthing is fine, so send the email!
$send = mail("nathan#nathanthompson.co.uk", "You have received an enquiry",
"<html>
<body>
<h3>Here is the information for the enquiry: </h3>
<br>
<p>Name: $name</p>
<p>Email: $email</p>
<p>Budget: $budget</p>
<p>Timeframe: $timeframe</p>
<br>
<p>Description of enquiry:</p>
<p>$desc</p>
</body>
</html>
", "Content-type: text/html; charset=iso-8859-1");
if ($send) {
header("Location: index.html");
} else {
die("An error occurred. Please return to the contact form and try again.");
}
} else {
die("An error occurred. Please return to the contact form and try again.");
}
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data, ENT_QUOTES);
return $data;
}
?>

CMS made simple - adding a php form

I'm trying to add a PHP form to a website I'm working on. Not real familiar with PHP, but I've put the file in the upload folder in the CMS.
I think I've linked the jQuery and other files correctly and I've edited the PHP file putting in emails etc. This one also calls on another PHP validation file.
Anyway it shows up normally and I can fill it out but it goes to a 404 page and doesn't work.
My question is, what linking convention do I use to link to the php file and is it in the right place? I use cPanel where the CMS is installed.
Instead of putting: action="url([[root_url]]/uploads/scripts/form-to-email.php"
should I just put: action="uploads/scripts/form-to-email.php"?
The page in question is here: www.edelweiss-web-design.com.au/captainkilowatt/
Also, anyone know a good captcha I can integrate with it...? Thanks!
<div class="contact-form">
<h1>Contact Us</h1>
<form id="contact-form" method="POST" action="uploads/scripts/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id='msg_submitting'><h2>Submitting ...</h2></div>
<div id='msg_submitted'><h2>Thank you !<br> The form was submitted Successfully.</h2></div>
</div>
Here is the php:
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?><?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://www.edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?>
I've added the php file.
So, in the action part, when I submit the form, it no longer gives me a 404 but takes me to a blank page with the 'form-to-email.php' page. However, the script is not working from what I can tell. Again, I know html and css, and little javascipt, but how php is meant to work...?
What am I doing wrong?
I would suggest using one of the modules for CMS instead of trying to build form in PHP from scratch. It is much more safer to use CMS buildin functions and that is the point of using the CMS in the first place. For CMS made simple the formbuilder module is here:
http://dev.cmsmadesimple.org/projects/formbuilder
Thanks for all the comments.
I found another form with a captcha (PHP) and preserved the whole structure by uploading it as is into CMSMS uploads folder.
I then used iframe to embed the form on my page, changed a couple of little details with the CSS and wording, and bob's your uncle, it works just fine.
For anyone interested, I used: www.html-form-guide.com/contact-form/creating-a-contact-form.html
This is free and I am certainly not trying to spam as I am in no way affiliated with this site or any sites associated with it.

PHP submit issue, variables changing?

I am trying to make a form for people to fill out that requests a service. They must for one of the fields enter a phone number. To ensure that the phone number is valid I have set up the PHP to send an SMS to the provided number using my providers API.
The sms sends okay and it sends with a PHP variable enclosed. (A Random int between 9999 and 99999.) This code is sent successfully but every submit the code changes as the function runs. The problem with this is that you receive the text but when you enter it in the code has already changed as you submitted the form to validate. I have tried using a button type in html but cant figure our how to run the PHP using it.
Below is the first form they fill out which sends the message.
<?php
$confirmcode = rand(9999, 99999);
//echo "<br/><br/><br/><br/><br/><br/>Confirmation Code:"."<br/><br/>$confirmcode<br/><br/><br/>";
if (isset($_POST['submit'])){
// Validation
//Check Name is non-blank
if( 0=== preg_match("/\S+/", $_POST['fname'])){
$errors['first_name'] = "Please enter your name.";
}
if (0=== preg_match("/^[\+0-9\-\(\)\s]{10,}+$/", $_POST['phone'])){
$errors['phone'] = "Please enter a phone number";
}
//Check Email has required symbols
if (0=== preg_match("/.+#.+\..+/", $_POST['email'])){
$errors ['email'] = "Please enter a valid email address.";
}
//End Validation
$errors = array();
$name = $_POST['fname'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$email = $_POST['email'];
//Sending Confirmation SMS code to confirm phone number.
// Declare the security credentials to use
$username = "############";
$password = "############";
// Set the attributes of the message to send
$message = "Hello " ."$name" ."Your confirmation code is: " ."$confirmcode".". " ."Please enter it .". "on he appraisal request form.";
$type = "1-way";
$senderid = "SanctuaryRE";
$to = $_POST['phone'];
// Build the URL to send the message to. Make sure the
// message text and Sender ID are URL encoded. You can
// use HTTP or HTTPS
$url = "http://api.directsms.com.au/s3/http/send_message?" .
"username=" . $username . "&" .
"password=" . $password . "&" .
"message=" . urlencode($message) . "&" .
"type=" . $type . "&" .
"senderid=" . urlencode($senderid) . "&" .
"to=" . $to;
// Send the request
$output = file($url);
// The response from the gateway is going to look like
// this:
// id: a4c5ad77ad6faf5aa55f66a
//
// In the event of an error, it will look like this:
// err: invalid login credentials
$result = explode(":", $output[0]);
//END SMS
header("Location: process.php");
}
?>
And the form they are pushed onto to confirm the code they were sent.
<html>
<div class="wrapper2">
<form action="" method="POST">
<input type="text" class="textfieldlong" placeholder="Confirmation Code" name="giventoken">
<input type="button" class="submit" value="Verify Phone Number" name="submit2" id="submit2">
</form>
</html>
<style>
.wrapper{
display:none;
}
</style>
</div>
<?php
include "index.php";
//$token = $_POST['giventoken'];
//if (!strcmp($confirmcode,$token)){
// echo "Match";
//}
echo "$confirmcode";
?>
The random int is generated right at the beginning. Please help! Thnx. :D
The random number is being created every time.
You will have to database the number for each specific user and then check when they enter the code. You cant expect the user to get the text and confirm immediately. The only real way to do this is to database it.
Setup a table with the userid and the code, then check when they confirm that you sent that code to that user.

How to redirect to another page in php?

Here is the code for registration. Values are inserted properly but page is not redirected to another page:
if(isset($_POST['submit'])){
$company_name = $_POST['company_name'];//check whether form is submitted or not
$email = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);//email validation
$password = sha1($_POST['password']);
$phone = $_POST['phone'];
$city = $_POST['city'];
$profession = $_POST['profession'];
check validation of email
if(!filter_var($email,FILTER_SANITIZE_EMAIL)){
echo 'invalid email';
}
else
{
$result = mysql_query("SELECT * FROM registerpro WHERE email = '$email'");selecting email from database
$data = mysql_num_rows($result);//check if there is result
if($data==0){
$qry = mysql_query("INSERT INTO registerpro (company_name,email,password,phone,city,profession) VALUES ('$company_name','$email','$password','$phone','$city','$profession')");
here i is the problem as page is not redirecting to another page so please tell me how to fix it
if($qry){
header("Location : company_info.php");//redirect to company_info
}
else`enter code here`
{
echo 'error';
}
}else{
echo 'invalid email';
}
}
}
?>
After registration page is not redirecting to company_info.
Remove extra space after Location
So, change
header("Location : company_info.php");//redirect to company_info
To:
header("Location: company_info.php");//redirect to company_info
// ^ here
I finally figured this out after struggling a bit. If you perform a web search on the PHP header() function you will find that it must be used at the very top of the file before any output is sent.
My first reaction was "well that doesn't help", but it does because when the submit button is clicked from the HTML input tag then the header() function will get run at the top.
To demonstrate this you can put a section of PHP code at the very top with the following line...
print_r($_POST);
When you then press the "Submit" button on your web page you will see the $_POST value change.
In my case I wanted a user to accept the Terms & Agreement before being redirected to another URL.
At the top of the file before the HTML tag I put the following code:
<?php
$chkboxwarn = 0;
/* Continue button was clicked */
if(!empty($_POST['continue']) && $_POST['continue']=='Continue'){
/* Agree button was checked */
if(!empty($_POST['agree']) && $_POST['agree']=='yes'){
header('Location: http://www.myurlhere.com');
}
/* Agree button wasn't checked */
else{
$chkboxwarn = 1;
}
}
?>
In the HTML body I put the following:
<form method="post">
<input type="checkbox" name="agree" value="yes" /> I understand and agree to the Terms above.<br/><br/>
<input type="submit" name="continue" value="Continue"/>
</form>
<?php
If($chkboxwarn == 1){
echo '<br/><span style="color:red;">To continue you must accept the terms by selecting the box then the button.</span>';
}
?>

How would I go about making this error message appear when form field is not right?

I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:
if(isset($_POST['submit'])) {
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
$error = "";
} else {
$error = "Please fill in the required fields.";
}
}
In the form, I have a span class like so:
<span class="error">'.$error.'</span>
I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?
Thanks so much for any help or tips!
In order to process the form while staying on the page, you will need to incorporate some AJAX. The easiest way to do this is to use a framework of some sort (recommend jQuery). This should give you some insight into how to develop such functionality. If you get stuck, we're here to help.
http://api.jquery.com/jQuery.post/
Following your current model, I am assuming you do not mean AJAX and that you merely mean the server side code and form cohabitate on the same script. You can set the action of the form to $_SERVER['PHP_SELF'] first to ensure the proper action attribute is set.
Are you echoing out the error message within the span, or is all that output being placed after an echo statement?
echo '<span class="error">'.$error.'</span>'
Or, if not in the PHP context outside of script
<span class="error"><? echo $error; ?></span>
Also, you may want to consider using a mature php mailing solution like PHP Mailer to help set headers and ensure more effective delivery.
You don't need any AJAX.
$error = '';
if (isset($_POST['submit'])) {
if ( <<< insert check for required fields >>> ) {
// handle form, send mail, etc
// you may want to redirect on success to prevent double posting
} else {
$error = "Please fill in the required fields.";
}
}
Well without the rest of the page I'm not sure why this isn't working already but you should post back to the same page not just an empty action. I would do it this way.
<?php
$error = $name = $email = $phone = $comment = "";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comment = $_POST['comment'];
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
} else {
$error = "Please fill in the required fields.";
}
}else{ ?>
<div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="emailMonthlySpecials.php">
<span class="error><?php echo $error; ?></span>
Name: <input name="name" type="text" value="<?php echo $name;?>"/><br />
Email: <input name="email" type="text" value="<?php echo $email;?>"/><br />
Phone Number: <input name="phone" type="text" <?php echo $phone;?>"/><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"><?php echo $comment;?></textarea><br /><br />
<input type="submit" value="Submit Email"/>
</form></div>
<?php } ?>
When I handle form validations, I tend to create an array to hold the error messages, like so:
<?php
$error = array();
if( $POST ){
# Form is Submitted
if( /* TRUE if "email" is empty */ ){
$error['email'] = 'Please provide an Email Address';
}elseif( /* TRUE if "email" is not a valid address */ ){
$error['email'] = 'Please provide a Valid Email Address';
}elseif( /* TRUE if "email" is already associated with a User */ ){
$error['email'] = 'The Provided Email Address is Already Taken';
}
...
if( count( $error )==0 ){
# No Error has been Recorded
# Do Successful Things
}
} /* Closing if( $_POST ){ */
Then within the presentation/display section, I have something like:
<?php if( count( $error )>0 ){ ?>
<div id="error">
The following Errors have occurred:
<ul>
<?php foreach( $error as $k => $v ){ ?>
<li><?php echo $k; ?>: <?php echo $v; ?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
And within the form, something like:
<input name="email"<?php echo ( $error['email'] ? ' class="error"' : '' ); ?> />
This means that:
Customised, multi-tiered error messages can be recorded.
A summary of the error messages can be shown.
Fields associated with the error messages can be marked.
Has worked well in my experience thusfar.
Yep, I think You have two methods to do that, as already explained above...
When the form is submitted to the same page (itself) using *$_SERVER['PHP_SELF']*, you can check weather each posted field is empty using empty() function. Then if they are not filled then set the variable $error and then use echo $error; at the span of error... If no any error you can assign the default message at the $error instead of the error... It should do what you need...
You can use AJAX and send a request to the page and set the error message. Then the page is not fully refreshed as it was before, but only the element you wanted to refresh. This is fast, but in most of the cases, first method is preferred, unless AJAX is a need..
What exactly you want to do? If you specify what's your actual need, it is possible to provide some sample code... (First method is already discussed)
Thank You.
ADynaMic
My suggest is to use ajax call when submit,
according to the answer come back, you update the span of error.
you can find a lot of examples in web like
http://jqueryfordesigners.com/using-ajax-to-validate-forms/
http://www.the-art-of-web.com/javascript/ajax-validate/

Categories