So I have a form with both javascript validation to check each field is filed and a jquery ajax script to stop the page reloading.
The PHP script is very simple and only emails the fields of the form.
The problem is I need to ONLY show the thank you message if each field is filled out, and at the moment it appears to be showing it when I just enter the name field.
It doesn't show it if i just enter either the email or message field though and I can't work out why (I'm bad at PHP).
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemail#address.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
if(mail($name,$email,$message,$headers)){
echo "<p>Thanks for your mail...</p>";
}
?>
Javascript that stops page reloading.
<script type="text/javascript">
$(document).ready(function() {
$(".contactus").submit(function() {
$.post("mail.php", $(".contactus").serialize(),
function(data) {
$("#formResponse").html(data);
}
);
return false;
});
});
</script>
Form validation.
<script type="text/javascript" language="JavaScript">
var FormName = "contactus";
var RequiredFields = "name,email,priority,message";
function ValidateRequiredFields()
{
var FieldList = RequiredFields.split(",")
var BadList = new Array();
for(var i = 0; i < FieldList.length; i++) {
var s = eval('document.' + FormName + '.' + FieldList[i] + '.value');
s = StripSpacesFromEnds(s);
if(s.length < 1) { BadList.push(FieldList[i]); }
}
if(BadList.length < 1) { return true; }
var ess = new String();
if(BadList.length > 1) { ess = 's'; }
var message = new String('\n\nThe following field' + ess + ' are required:\n');
for(var i = 0; i < BadList.length; i++) { message += '\n' + BadList[i]; }
alert(message);
return false;
}
function StripSpacesFromEnds(s)
{
while((s.indexOf(' ',0) == 0) && (s.length> 1)) {
s = s.substring(1,s.length);
}
while((s.lastIndexOf(' ') == (s.length - 1)) && (s.length> 1)) {
s = s.substring(0,(s.length - 1));
}
if((s.indexOf(' ',0) == 0) && (s.length == 1)) { s = ''; }
return s;
}
// -->
</script>
And the form
<form action="mail.php" id="myform" class="contactus" onsubmit="return ValidateRequiredFields(); this.submit(); this.reset(); return false;" name="contactus" method="POST">
<p class="floatleft" style="width:200px; background-color:#FF0000; height:50px; line-height:50px; margin:0; padding:0;">Nameeeeee</p> <input class="sizetext" type="text" maxlength="10" name="name">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Email</p> <input class="sizetext" type="text" maxlength="10" name="email">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Telephone</p> <input class="sizetext" type="text" maxlength="10" name="telephone">
<p>Priority</p>
<select name="priority" size="1">
<option value="Low">Low</option>
<option value="Normal">Normal</option>
<option value="High">High</option>
<option value="Emergency">Emergency</option>
</select>
</select>
<p>Message</p><textarea name="message" rows="6" cols="25"></textarea><br />
<br />
<input class="buttonstyle" type="submit" value="Send">
</form>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$check = array('name', 'email', 'priority', 'message', 'telephone');
$send = true;
foreach($check as $key => $value){
if(empty($_POST[$value])){
$send = false;
}
}
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemail#address.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
if($send && mail($recipient, $subject, $formcontent, $mailheader)){
echo "<p>Thanks for your mail...</p>";
}
else{
die('Error!');
}
Well, the most easier way would be to check if your POST fields are present and not empty. Probably there is a more elegant solution if you want to check every field individually, but here goes:
if (isset($_POST['name']) && !empty($_POST['name']) && isset($_POST['email']) && !empty($_POST['email']) && isset($_POST['message']) && !empty($_POST['message'])) {
if(mail($name,$email,$message,$headers)){
echo "<p>Thanks for your mail...</p>";
}
}
You need to wrap your code around
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemail#address.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
$mail = #mail($recipient, $subject, $formcontent, $mailheader);
if($mail){
echo "<p>Thanks for your mail...</p>";
}
else
{
echo "Error Sending Mail " ;
}
}
Related
I am trying to display the name from the input field on a contact form to show the name that was entered after the email was submitted, I have changed headers in php and it has changed from cgi-mailer to unbknown sender? How do i get it to display the name of the person whosent the email from the contact form?
Thanks
form process php that controls validtion etc
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
$from = $_POST['name1'];
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Conotact form html
<?php include('form_process.php');
/*if (isset($_POST['contact-submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "secretkeygoogle";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADOR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
}else{
}
}*/
?>
<div class="home-btn"><i class="fas fa-home"></i></div>
<div class='grey'>
<div class="container-contact">
<form id="contact" method="post">
<div id="column-contact-left">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset>
<input placeholder="Your name" type="text" tabindex="1" name="name1" value="<?= $name ?>" autofocus>
</fieldset>
<span class="error"><?= $name_error ?></span>
<fieldset>
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2" >
</fieldset>
<span class="error"><?= $email_error ?></span>
</div>
<div id="column-contact-right">
<fieldset>
<textarea placeholder="Type your Message Here...." name="message" value="<?= $message ?>" tabindex="3" ></textarea>
</fieldset>
<div class="g-recaptcha" data-sitekey="needtoinput" ></div>
<span class="success"><?= $success; ?></span>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</div>
</form>
</div>
</div>
New form p[rocess php with seperate mail function
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
$from = $_POST['name1'];
$headers = "From:" . $from;
if (isset($_POST['submit'])) {
mail($headers);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
LATEST PHP for the last comment i made
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
You must have the required fields on your form, then if you want, ask for the name too.
<?php
function defaultMailing($to, $subject, $txt, $headers){
if(mail($to, $subject, $txt, $headers)) return true; else return false;
}
?>
on the other part (where your form action):
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
//you don't need name, but if you asked for on the form:
$msg = "thanks, ".$_POST['name']." for your message, your request will be answered soon.";
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $txt, $headers);
//do whatever you want with $msg or with $_POST['name'];
If you want to insert the posted name on the message, simply modify $txt var setting the $_POST['name'] wherever you want and then, proceed with defaultMailing call, for example:
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
$name = $_POST['name'];
$mailMessage = $name.' '.$txt;
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $mailMessage, $headers);
Settles for the email being the from sender as it appears that a from value has to be a valid email address
if ($name_error == '' and $email_error == '' and ($res['success']) ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)) {
$sent = "Message sent";
$name = $email = $message = '';
}
I'm trying to make $name, $email, and $message validate in one script without making them all look like a error (make them all a red color) rather than the one that is actually incorrect.
Her is the code I'm using:
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'matt.owen#example.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
} else {
exit(json_encode(array('error' => 1)));
}
if ($name == "") {
exit(json_encode(array('error' => 1)));
} else {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
}
?>
AJAX Script:
var sendEmail = function(){
var url = 'main.php';
$.ajax({
url : url,
type : "POST",
dataType : "JSON",
data : $('#contact-form').serialize(),
success : function(response) {
if (response.error == 0) {
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else {
$('#email-input').css('color', 'red');
alert('ERROR MESSAGE');
}
}
})
return false;
}
HTML:
<div id="contact">
<div class="container">
<form id="contact-form" method="post" onsubmit="return sendEmail()">
<h1>Contact Form</h1>
<fieldset>
<input placeholder="Your Name" type="text" name="name" id="name-input" required value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
</fieldset>
<fieldset>
<input placeholder="Your Web Site (optional)" type="url" name="site" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name="message" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>"></textarea>
</fieldset>
<fieldset>
<button type="submit" id="contact-submit" name="submit">Submit</button>
</fieldset>
</form>
</div>
</div>
Just send back a list of bad elements, instead of a blanket error statement
<?php
// ...
$errors = [];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = "email";
}
if ($name == "") {
$errors[] = "name";
}
if ($message == "") {
$errors[] = "message";
}
if (count($errors) === 0) {
mail($to, $email_subject, $email_body,$headers);
}
echo json_encode($errors);
//...
Then in your JS:
success : function(response) {
if (response.length == 0) {
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else {
for (var i = 0; i < response.length; i++) {
$('#' + response[i] + '-input').css('color', 'red');
alert('ERROR MESSAGE');
}
}
}
My Javascript is a bit rusty but that should do the trick.
Note that <textarea> doesn't have a value attribute, contents are added as a child text node. You should also use htmlspecialchars() on all output from PHP to prevent XSS problems.
in your js:
$erro = 0;
if(document.getElementById("name-input").value == null or document.getElementById("name-input").value == ""){
$erro = 1;
document.getElementById("name-input").style.borderColor = "red";
}
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
}
...
if($erro == 0){
//run ajax
}
You can put a bit more html code to make a hidden textbox appear using.
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
document.getElementById("id_erro1").style.visibility = "visible";
}
create in your html:
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
<input type="hidden" name="error_mensage1" id="id_erro1" value="Required field" >
</fieldset>
Use css to Spice up.
I am trying to make an contact form for my website and I am using the following code. I don't know why the selector keeps reseting when the text fields don't.
Anyone know a soultion for this? Or what I am doing wrong.
( It resets when the error check is done, and fails )
<?php
session_start();
$php_self = $_SERVER['PHP_SELF'];
// on submit
if( isset($_POST[name]) && isset($_POST[email]) && isset($_POST[message]) && isset($_POST[captcha]) ){
$name = $_POST[name];
$email = $_POST[email];
$telefon = $_POST[telefon];
$option = $_POST[option];
$message = $_POST[message];
$captcha = $_POST[captcha];
$error = 0;
// name
if( $name == "" ){ $error ++; $error_name = "class='error'"; }
// email
if( $email == "" ){ $error ++; $error_email = "class='error'"; }
// message
if( $message == "" ){ $error ++; $error_message = "class='error'"; }
// captcha
if( $captcha == "" || $captcha != $_SESSION[captcha]){ $error ++; $error_captcha = "class='error'"; }
// no error, send email
if( $error == 0){
// your email address
$address = "surrealcmstest#outlook.com";
// email subject
$subject = "x , Nytt Meddelande \r\n";
// email content
$content = "Namn: $name \r\nE-postadress: $email \r\nTelefon Nr: $telefon \r\nKontakta mig via: $option \r\nMeddelande: $message";
// html email
$email_content = "".$subject."";
$email_content .= "";
$email_content .= $content;
$email_content .= "";
// send email
mail($address, $subject, $email_content, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
// reset variables
$name = ""; $email = ""; $message = "";
$mail_sent = 1;
}
}
// captcha
$num = rand(1, 20);
$num2 = rand(1, 9);
$verif = $num . " + " . $num2;
$_SESSION[captcha] = $num + $num2;
if( $mail_sent == 1 ){
echo "<div class=","sucess",">Ditt meddelande har skickats, vi återkommer så fort som möjligt.</div>";
} else {
echo "
<form action='".$php_self."' method='post'>
<p><span class='required'>* är obligatoriska fält.</span></p>
<p><strong>Namn:</strong> <span class='required'>*</span></p>
<input type='text' ".$error_name." name='name' value='".$name."'>
<p><strong>E-postadress:</strong> <span class='required'>*</span></p>
<input type='email' ".$error_email." name='email' value='".$email."'>
<p><strong>Telefon Nr:</strong></p>
<input type='telefon' name='telefon' value='".$telefon."'>
<p><strong>Kontakta mig via:</strong></p>
<select name='option'>
<option value='-'>-</option>
<option value='Telefon'>Telefon</option>
<option value='E-post'>E-post</option>
</select>
<p><strong>Meddelande:</strong> <span class='required'>*</span></p>
<textarea ".$error_message." name='message'>".$message."</textarea>
<p><strong>Hur mycket är ".$verif."?</strong> <span class='required'>*</span></p>
<input type='text' ".$error_captcha." name='captcha' value=''><br/>
<button>Skicka</button>
</form>";
}
?>
You have to add a check for each option Tag like you do with the inputs and load from the $_POST value before...
$option = $_POST['option'];
And in the select
<select name='option'>
<option value='-'>-</option>
<option value='Telefon' ".($option == 'Telefon' ? "selected":"").">Telefon</option>
<option value='E-post' ".($option == 'E-post'? "selected" : "").">E-post</option>
</select>
Edited:
Changed it to the inline string statement for the output string that the OP is generating...
I have website (dastiche.kz) and there is newsletter subscription. I have modified a bit my subscription, adding some "iframe", so that echo would appear without redirecting to another page. Everything now works well, but I now got annoying problem. Everytime I go to my main page(where the subscription form is located) or just refresh it, php is triggered and I receive blank email as though someone has made subscription. What did I do wrong?
<iframe name="myiframe" src="myiframe.php" width="100%" height="60px" frameborder="0"></iframe>
<form method="POST" action="myiframe.php" class="subscribe" target="myiframe">
<p><input type="text" name="Name" maxlength="10" style="font-family:'Times New Roman', Times, serif" value="Ваше имя" onfocus="if (this.value == 'Ваше имя') {this.value = '';}" onblur="if (this.value == '') {this.value ='Ваше имя';}" class="line"></p>
<p><input type="email" name="Email" maxlength="40" style="font-family:'Times New Roman', Times, serif" value="Ваш email" onfocus="if (this.value == 'Ваш email') {this.value = '';}" onblur="if (this.value == '') {this.value ='Ваш email';}" class="line"></p>
<p><input type="image" value="submit" name="Submit" src="img/subscribe.png" class="imgsub"></p>
</form>
<?php
Header("Content-Type: text/html; charset=utf-8");
$recipient = "order#dastiche.kz";
$subject = "Subscriber";
$name = $_POST['Name'];
$email = $_POST['Email'];
$location = "index.html";
$sender = $recipient;
$body .= "Name: ".$_REQUEST['Name']." \n";
$body .= "Email: ".$_REQUEST['Email']." \n";
if (($name != "") and ($email != ""))
// Если существуют проверяем...
{
if ((strlen($name) >= 2) and (strlen($name) <= 25))
{
$name = stripslashes($name);
$name = html_entity_decode($name);
$name = strip_tags($name);
}
else
{
echo " something is wrong with name field ";
echo "<center><input name='back' type='button' value='get back'
onclick= 'javascript:history.back()'></center>";
}
if (eregi("^[._a-zA-Z0-9-]+#[.a-zA-Z0-9-]+.[a-z]{2,6}$", $email))
{
$email = stripslashes($email);
$email = htmlspecialchars($email);
$email = strip_tags($email);
}
else
{
echo "There are some mistakes in the \"E-mail\" field";
echo "<center><input name='back' type='button' value='try again'
onclick= 'javascript:history.back()'></center>";
}
}
// Если не существуют выводим сообщение...
else
{
echo "Заполните следующие поля:";
}
if (($name) and ($email))
{
echo "Спасибо за подписку!";
}
mail( $recipient, $subject, $body, "From: $sender" ) or die ("Mail could not be sent.");
?>
As i Commented put a condition above of your code
if(isset($_POST['Submit']))
{
// here put your complete php code
}
This will check if the POST request in received with the name of Submit. so the code will execute when you press the submit button Like
<?php
if(isset($_POST['Submit']))
{
Header("Content-Type: text/html; charset=utf-8");
$recipient = "order#dastiche.kz";
$subject = "Subscriber";
$name = $_POST['Name'];
$email = $_POST['Email'];
$location = "index.html";
$sender = $recipient;
$body .= "Name: ".$_REQUEST['Name']." \n";
$body .= "Email: ".$_REQUEST['Email']." \n";
if (($name != "") and ($email != ""))
// ???? ?????????? ?????????...
{
if ((strlen($name) >= 2) and (strlen($name) <= 25))
{
$name = stripslashes($name);
$name = html_entity_decode($name);
$name = strip_tags($name);
}
else
{
echo " something is wrong with name field ";
echo "<center><input name='back' type='button' value='get back'
onclick= 'javascript:history.back()'></center>";
}
if (eregi("^[._a-zA-Z0-9-]+#[.a-zA-Z0-9-]+.[a-z]{2,6}$", $email))
{
$email = stripslashes($email);
$email = htmlspecialchars($email);
$email = strip_tags($email);
}
else
{
echo "There are some mistakes in the \"E-mail\" field";
echo "<center><input name='back' type='button' value='try again'
onclick= 'javascript:history.back()'></center>";
}
}
// ???? ?? ?????????? ??????? ?????????...
else
{
echo "????????? ????????? ????:";
}
if (($name) and ($email))
{
echo "??????? ?? ????????!";
}
mail( $recipient, $subject, $body, "From: $sender" ) or die ("Mail could not be Sent");
}
?>
I am new to php and I have post forms down but not I want some of my imput fields to be required.
I want this form to force the user to fill out the required fields but then be directed to my process.php page which will send me an email with the data the form collected. Right now the data is being posted at the bottom of the page. Please help me direct the data to an email.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["website"]))
{$website = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
if (empty($_POST["gender"]))
{$genderErr = "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</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
I have the code to collect that data and email it. i just don't know how to get the form to validate and then direct to the process.php page.
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$comment = $_POST['comment'];
$gender = $_POST['gender'];
$to = 'str#xxxxxxxx.com';
$subject = 'Executive Plaza Contact Form Response';
$message.= "Name: $name \n";
$message.= "Email: $email \n";
$message.= "email: $email \n";
$message.= "comment: $comment \n";
$message.= "gender: $gender \n";
$headers = "From: Eleven55\r\n";
mail($to, $subject, $message, $headers);
header('Location: thank-you.php');
Read up on the PHP mail() function here. It is basic and should get you started.
$to='you#domain.com';
$subject='Form data';
$body = "{$name} says {$comment}. \n Contact {$name} at {$email} or {$website}. \n {$name} is a {$gender}";
mail($to, $subject, $body);
http://php.net/manual/en/function.mail.php
$to='youremail#yourdomain.com';
$subject='Form data';
$body = "Name :$name \n ...";
mail($to, $subject, $body);
Read the mail function documentation for more info
My bad. Do this
document.forms.onsubmit = function(){ //onsubmit event
//validate form data using getElementById().val and so on
if(formdataisnotvalid){
alert('descriptive error message');
return false; // this will prevent the form from submitting
}