I got a template online... They included this contact.php - And how do I add extra fields so this contact.php will send it to me.
<?php
if(!$_POST) exit;
$email = $_POST['email'];
//$error[] = preg_match('/\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i', $_POST['email']) ? '' : 'INVALID EMAIL ADDRESS';
if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."#"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$email )){
$error.="Invalid email address entered";
$errors=1;
}
if($errors==1) echo $error;
else{
$values = array ('name','email','message');
$required = array('name','email','message');
$your_email = "myemail#live.ca";
$email_subject = "New Message: ".$_POST['subject'];
$email_content = "new message:\n";
foreach($values as $key => $value){
if(in_array($value,$required)){
if ($key != 'subject' && $key != 'company') { if( empty($_POST[$value]) ) { echo 'PLEASE FILL IN REQUIRED FIELDS'; exit; }
}
$email_content .= $value.': '.$_POST[$value]."\n";
}
}
if(#mail($your_email,$email_subject,$email_content)) {
echo 'Message sent!';
} else {
echo 'ERROR!';
}
}
?>
The HTML contact page is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
telephone: $('#telephone').val(),
company: $('#company').val(),
subject: $('#subject').val(),
message: $('#message').val()
},
function(data){
$('#contactform #submit').attr('disabled','');
$('.response').remove();
$('#contactform').before('<p class="response">'+data+'</p>');
$('.response').slideDown();
if(data=='Message sent!') $('#contactform').slideUp();
}
);
return false;
});
});
// ]]>
</script>
</head>
<body>
<div class="main">
<div class="blok_header">
<div class="header">
<div class="search">
</div>
<div class="clr"></div>
<div class="withe_bg">
<div class="logo"></div>
<div class="menu"> </div>
<div class="clr"></div>
<div class="body">
<h3> </h3>
<p> </p>
<div class="left">
<h2>Send us a Message:</h2>
<p>Please use this convenient form to your send your message, and we will get back to you shortly.</p>
<form action="contact.php" method="post" id="contactform">
<ol>
<li>
<label for="name">Name <span class="red">*</span></label>
<input id="name" name="name" class="text" />
</li>
<li>
<label for="telephone">Telephone <span class="red"></span></label>
<input id="telephone" name="telephone" class="text" />
</li>
<li>
<label for="email">Your email <span class="red">*</span></label>
<input id="email" name="email" class="text" />
</li>
<li>
<label for="company">Company</label>
<input id="company" name="company" class="text" />
</li>
<li>
<label for="subject">Subject</label>
<input id="subject" name="subject" class="text" />
</li>
<li>
<label for="message">Message <span class="red">*</span></label>
<textarea id="message" name="message" rows="6" cols="50"></textarea>
</li>
<li class="buttons">
<input type="image" name="imageField" id="imageField" src="images/send.gif" class="send" />
<div class="clr"></div>
</li>
</ol>
</form>
</div>
<div class="right last">
<p> </p>
<p>
</p>
</div>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
</div>
<div class="clr"></div>
</div>
<div class="FBG">
<div class="FBG_resize">
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
</div>
<div class="clr"></div>
</div>
<div class="FBG">
<div class="FBG_resize">
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
<div class="footer">
<div class="footer_resize">
<p class="leftt"> </p>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
</body>
</html>
And still does not work.....
this isn't the form itself, it's the form processor. you probably have an HTML file somewhere with the form, posting to this contact.php file.
anyway, it looks like you have to match the # of fields you're requesting in the form to the # of items (with the correct names) in the $values array. It also looks like you can require certain ones in the $required array.
change the $your_email to your email address.
you should get the emails through the form.
does that answer your question? It wasn't terribly specific.
The fix is:
edit the: $required = array('name','email','telephone','message');
And it works... 100% - thanks all...
If you want it to email to multiple people, you should take a look at the parameters section (the To section)here. This will go in your
$your_email = "myemail#live.ca";
Here's an example:
$your_email = "<user#example.com>, Another User <anotheruser#example.com>";
That should send it to user#example.com and anotheruser#example.com
You mean you want the contact mail to be sent to you also,right? if so try the following code. mail is the php mail function which done the trick. For more reference you can check the MANUAL.
<?php
$email = $_POST['email'];
//$error[] = preg_match('/\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i', $_POST['email']) ? '' : 'INVALID EMAIL ADDRESS';
if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."#"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$email )){
$error.="Invalid email address entered";
$errors=1;
}
if($errors==1) echo $error;
else{
$values = array ('name','email','message');
$required = array('name','email','message');
$your_email = "seanbridge#live.ca";
$email_subject = "New Message: ".$_POST['subject'];
$email_content = "new message:\n";
foreach($values as $key => $value){
if(in_array($value,$required)){
if ($key != 'subject' && $key != 'company') { if( empty($_POST[$value]) ) { echo 'PLEASE FILL IN REQUIRED FIELDS'; exit; }
}
$email_content .= $value.': '.$_POST[$value]."\n";
}
}
if(#mail($your_email,$email_subject,$email_content)) {
echo 'Message sent!';
} else {
echo 'ERROR!';
}
$myEmail = "myemai#your.com";//put your email address here
if(#mail($myEmail,$email_subject,$email_content)) {
echo 'Message sent!';
} else {
echo 'ERROR!';
}
}
?>
Related
I'm new to PHP and I've got issue in my contact form. When I press "Submit" in my form it skips (somewhere, I don't know where and why it happens) to other site, and conditions are not checked by the php code. What's more, you can type wrong answer in "human recognizer" and it will still send and email.
I was looking for som bad declarations or wrong syntax, but all seems to be good. I assume that also my contact.php responds properly if it sends an email (but without checking conditions).
I don't know if it's connected but my modal window in it also doesn't want to close (but on the other site the same code works fine, when there is other form withoud "action=contact.php" field).
My main head.php:
<!--HEAD-->
<head>
<title>X</title>
<!--META-->
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="SitePoint">
<!--CSS-->
<link id="theme" rel="stylesheet" href="css/light.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Font Awesome -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<!--END OF HEAD-->
<body>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script src="js/dropdown.js"></script>
<script src="js/scrolling-nav.js"></script>
<script src="js/theme-switch.js"></script>
<script src="js/nav-position.js"></script>
<nav id="mainNav">
<bar>
<i id="hamburger" class="fa fa-bars" aria-hidden="true"></i>
</bar>
<ul id="menu">
<li>Main</li>
<li>Generator</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
<section id = "main" >
<div class = "content">
<h1>Hello!</h1>
<p>:)</p>
</div></section>
<section id = "generator">
<div class = "content">
<h1>Generator</h1>
<form id="generator-form" ="form-horizontal" role="form" method="post" action="generator.php">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<label for="idCardNumber" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="idCardNumber" name="idCardNumber" placeholder="Student ID Card Number" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>
</div></section>
<section id = "about">
<div class = "content">
<h1>About</h1>
<p></p>
</div></section>
<section id="contact">
<div class="content">
<h1>Contact</h1>
<p><a class="btn btn-default btn-lg" href="#contact-form">Contact Us</a></p>
<p><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d5122.204450340393!2d19.91387757798398!3d50.065647167696376!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47165ba756b59b21%3A0xb20c8dba21b317d1!2sAkademia+G%C3%B3rniczo-Hutnicza+im.+Stanis%C5%82awa+Staszica+w+Krakowie!5e0!3m2!1spl!2spl!4v1511628584066" width="500rem" height="500rem" frameborder="0" style="border:0" allowfullscreen></iframe></p>
</div>
</section>
<footer>
<label class="switch">
<input type="checkbox" onchange=" switchTheme(this)">
<span class="slider"></span>
</label>
<p>Copyright©2017 for </p>
</footer>
<!--SIGN UP-->
<div id="contact-form" class="modal-window">
<div>
Close
<form action="contact.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<p class="text-danger"><?php echo $errName; ?></p>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<p class="text-danger"><?php echo $errEmail; ?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="4" name="message" value="<?php echo htmlspecialchars($_POST['message']);?>"></textarea>
<p class="text-danger"><?php echo $errMessage; ?></p>
</div>
<div class="form-group">
<label for="human">1 + 1 = ?</label>
<input type="text" class="form-control" id="human" name="human" pattern=".{1,}" required title="At least 1 character required" placeholder="Your Answer">
<p class="text-danger"><?php echo $errHuman; ?></p>
</div>
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary btn-lg"></input>
<div class="form-group">
<?php echo $result; ?>
</div>
</form>
</div>
</div>
<!--END SIGN UP-->
<!--CONTACT FORM-->
<div id="contact-form" class="modal-window">
<a title="Close" class="modal-close">Close</a>
<form id="contactForm" role="form" method="post" action="contact.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" pattern=".{3,}" required title="At least 3 characters required" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" pattern=".{3,}" required title="At least 3 characters required" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="4" pattern=".{3,}" required title="At least 3 characters required" name="message">
<?php echo htmlspecialchars($_POST['message']);?>
</textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
<div class="form-group">
<label for="human">1 + 1 = ?</label>
<input type="text" class="form-control" id="human" name="human" pattern=".{1,}" required title="At least 1 character required" placeholder="Your Answer">
<p class='text-danger'>$errHuman</p>
</div>
<input name="submit" type="submit" value="Send" class="btn btn-primary btn-lg">
<div class="form-group">
<?php echo $result; ?>
</div>
</form>
</div>
<!--CONTACT FORM-->
</body>
</html>
My contact.php code:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$human = intval($_POST['human']);
$from = 'Generator Contact';
$to = 'kamykx#gmail.com';
$subject = 'Message from AGH Generator Form';
$body ="From: $name\n E-Mail: $email\n Message:\n $message";
//CHECK NAME
if (!$name || empty($name)) {
$errName = 'Please enter your name';
}
//CHECK EMAIL
if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
$errEmail = 'Please enter a valid email address';
}
//CHECK MESSAGE
if (!$message || empty($message)) {
$errMessage = 'Please enter your message';
}
//CHECK IF USER IS NOT A BOT
if ($human !== 2 || $human !=2) {
$errHuman = 'Please... proof that you are not a bot :>';
}
//SEND THE EMAIL IF THERE ARE NO EXISTING ERRORS
if (!empty($errName) && !empty($errEmail) && !empty($errMessage) && !empty($errHuman)) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! We will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
header("Location: home.php");
}
}
?>
EDIT:
I've done improvements in my php code (there was logical problem in line error fields are empty: was -> if(!empty($errName)) but should be -> if(empty($errName)).
But I've still got and issue. I've compressed the code in order to stay on the same page after contact form submit, but when we click the "submit" button nothing appears (no errors are displayed), page only refreshes and open the form again. What's wrong now? NEW CODE:
<!DOCTYPE HTML>
<html lang="en">
<!--HEAD-->
<head>
<title>AGH Application for entry with ECTS deficit generator</title>
<!--META-->
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="SitePoint">
<meta name="Description" content="It is simple PDF generator for sing with lack of ECTS for another term" />
<meta name="Keywords" content="ECTS, deficit, deficyt, Poland, Cracow, generator, application, form, pdf, AGH, UST, Akademia, Górniczko, Hutnicza, University, S cience, Technology, Polska, Kraków, " />
<!--CSS-->
<link id="theme" rel="stylesheet" href="css/dark.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Font Awesome -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<!--END OF HEAD-->
<body>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script src="js/dropdown.js"></script>
<script src="js/scrolling-nav.js"></script>
<script src="js/theme-switch.js"></script>
<script src="js/nav-position.js"></script>
<nav id="mainNav">
<bar>
<i id="hamburger" class="fa fa-bars" aria-hidden="true"></i>
</bar>
<ul id="menu">
<li>Main</li>
<li>Generator</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
<section id = "main" >
<div class = "content">
<h1>Hello!</h1>
<p>Welocome to The AGH Application for entry with ECTS deficit generator website. We hope that you use it just for fun :)</p>
</div></section>
<section id = "generator">
<div class = "content">
<h1>Generator</h1>
</div></section>
<section id = "about">
<div class = "content">
<h1>About</h1>
<p>This webapge was created as a project for the Web Technologies. The main reason why it exists is that very common among Students is that they want to apply for entry on another term with ECTS deficit. This site will help students and AGH employees by generating PDF application. We hope that everything at AGH will be fast and growing in the future. We want to make our students life BETTER! </p>
</div></section>
<section id="contact">
<div class="content">
<h1>Contact</h1>
<p><a class="btn btn-default btn-lg" href="#contact-form">Contact Us</a></p>
<?php echo $result; ?>
<p><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d5122.204450340393!2d19.91387757798398!3d50.065647167696376!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47165ba756b59b21%3A0xb20c8dba21b317d1!2sAkademia+G%C3%B3rniczo-Hutnicza+im.+Stanis%C5%82awa+Staszica+w+Krakowie!5e0!3m2!1spl!2spl!4v1511628584066" width="500rem" height="500rem" frameborder="0" style="border:0" allowfullscreen></iframe></p>
</div>
</section>
<footer>
<label class="switch">
<input type="checkbox" onchange=" switchTheme(this)">
<span class="slider"></span>
</label>
<p>Copyright©2017 Marcin Kamiński for AGH </p>
</footer>
<!--SIGN UP-->
<?php
if (isset($_POST["send"])) {
$name = $_POST['name']; //Getting variable from form
$email = $_POST['email']; //Getting variable from form
$message = $_POST['message']; //Getting variable from form
$human = intval($_POST['human']); //Getting variable from form
$from = 'Generator Contact'; //Set sender
$to = 'kamykx#gmail.com'; //Where to send an email
$subject = 'Message from AGH Generator Form'; //Set the subject of email
$errName = $errEmail = $errMessage = $errHuman = ''; //Values of errors
$body ="From: $name\n E-Mail: $email\n Message:\n $message"; //Body of email
//CHECK NAME
if (empty($name)) {
$errName = 'Please enter your name';
}
//CHECK EMAIL
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
$errEmail = 'Please enter a valid email address';
}
//CHECK MESSAGE
if (empty($message)) {
$errMessage = 'Please enter your message';
}
//CHECK IF USER IS NOT A BOT
if ($human !== 2 || $human !=2) {
$errHuman = 'Please... proof that you are not a bot :>';
}
//SEND THE EMAIL IF THERE ARE NO EXISTING ERRORS
if (empty($errName) && empty($errEmail) && empty($errMessage) && empty($errHuman)) {
if (mail($to, $subject, $body, $from)) {
$result = '<div class="alert alert-success">Thank You! We will be in touch</div>';
}
else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
<div id="contact-form" class="modal-window">
<div>
Close
<form id="contactForm" role="form" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<p class="text-danger"><?php echo $errName; ?></p>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<p class="text-danger"><?php echo $errEmail; ?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="4" name="message" value="<?php echo htmlspecialchars($_POST['message']);?>"></textarea>
<p class="text-danger"><?php echo $errMessage; ?></p>
</div>
<div class="form-group">
<label for="human">1 + 1 = ?</label>
<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
<p class="text-danger"><?php echo $errHuman; ?></p>
</div>
<button id="send" name="send" type="submit" value="Send" class="btn btn-default btn-lg">Send</button>
</form>
</div>
</div>
<!--END SIGN UP-->
</body>
</html>
Your issue is in the logic of this line:
if (!empty($errName) && !empty($errEmail) && !empty($errMessage) && !empty($errHuman)) {
Basically this is saying if everything is wrong, send the email. The not empty check means that there was an error and the variable now holds the error string.
Instead, you just need to create the variables as an empty string and check if they are still empty:
$errName = $errEmail = $errMessage = $errHuman = '';
// CHECK NAME... etc... all the checks
if (empty($errName) && empty($errEmail) && empty($errMessage) && empty($errHuman)) {
However, you're not displaying the error to the user, and you're ending up with a bunch of loose variables. I recommend a slightly different approach using an array of errors...
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
$errors = [];
//CHECK NAME
if (!$name || empty($name)) {
$errors['name'] = 'Please enter your name';
}
//CHECK EMAIL
if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
$errors['email'] = 'Please enter a valid email address';
}
//etc...
if (empty($errors)) {
//send email
} else {
$result = '<div class="alert alert-danger">Sorry there was an error sending your message:<br>';
foreach ($errors as $key => $error) {
$result .= $error . '<br>';
}
$result .= '</div>';
}
However, if you immediately call a header function after this, the user will never see the error or get a chance to fix it. You can use a query string to send errors back to head.php and display them.
(FYI, the action of a form sends all the POST data to that file, and if there is no action specified, then the form posts to itself.)
I am very new to php and I need help.
I have developed a php contact page but I have problems with validation when there is a field blank. When I test my validation it opens the php page and displays the message instead of showing an alert .Please see picture below
Validation problem
Here is my code:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Exam Portal </title>
<!--META-->
<meta name="viewport" content="width=device-width initial-scale=1.0">
<!--FONT-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300,700,500' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Merriweather:400,300' rel='stylesheet' type='text/css'>
<!--CSS-->
<link rel="stylesheet" type="text/css" href="css/grid.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/responsive.css">
<link rel="stylesheet" type="text/css" href="css/animate.css">
</head>
<body>
<div class="se-pre-con">
<div class="cssload-container">
<div class="cssload-loading"><i></i><i></i><i></i><i></i></div>
</div>
</div>
<header style="background-color:black" id="top">
<div class="container">
<div class="header-bottom">
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-5 col-xs-12">
<div class="logo">
<a href="#banner" data-scroll><img src="img/logo.png" alt="" /></a>
</div>
</div>
<div class="col-lg-8 col-md-8 col-sm-7 col-xs-12">
<nav class="nav-collapse">
<ul>
<li class="menu-item"><a href="index.html" data-scroll>HOME</a></li>
<li class="menu-item"><a href="aboutus.html" data-scroll>ABOUT US</a></li>
<li class="menu-item"><a href="howdoesitwork.html" data-scroll>HOW DOES IT WORK</a></li>
<li class="menu-item"><a href="whousesexamportal.html" data-scroll>WHO USES EP</a></li>
<li class="menu-item"><a href="gallery.html" data-scroll>GALLERY</a></li>
<li class="menu-item"><a href="news.html" data-scroll>NEWS</a></li>
<li class="menu-item active"><a href="contactus.html" class="btnstart" data-scroll>CONTACT US </a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</header> <br><br><br><br><br><br>
<section id="contact2">
<div id="contact-us-map">
<iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://www.google.com/maps/embed?pb=!1m23!1m12!1m3!1d114610.04099879299!2d28.110395278010596!3d-26.145762465850492!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m8!3e6!4m0!4m5!1s0x1e9513bfa79eae3f%3A0xabf626720595f367!2shighway+gardens+office+park!3m2!1d-26.1457794!2d28.1804356!5e0!3m2!1sen!2sza!4v1497301543030"></iframe>
<br />
<small>
</small>
</iframe>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="contact_area">
<div class="client_title">
<hr>
<h2>We Would Love To Hear From You</h2>
</div>
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="contact_left wow fadeInLeft">
<form method="post" class="submitphoto_form" action="contact.php" id="contactpage">
<input type="text" class="form-control wpcf7-text" placeholder="Your name" name="name" id="name">
<input type="mail" class="form-control wpcf7-email" placeholder="Email address" name="email" id="email">
<input type="text" class="form-control wpcf7-text" placeholder="Subject" name="subject" id="subject">
<textarea style="height:300px" class="form-control wpcf7-text" placeholder="What would you like to tell us" name="message" id="message"></textarea>
<input type="submit" value="Submit" class="wpcf7-submit photo-submit" name="send" id="send">
</form>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="contact_right wow fadeInRight">
<img src="img/phone_icon.png" alt="img">
<p>Say hello! </p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<footer>
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="footersocial">
<i class="fa fa-twitter" aria-hidden="true"></i>
<i class="fa fa-facebook" aria-hidden="true" ></i>
<i class="fa fa-instagram" aria-hidden="true"></i>
<i class="fa fa-dribbble" aria-hidden="true"></i>
<i class="fa fa-gg-circle" aria-hidden="true"></i>
</div>
</div>
</div>
</div>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="js/fixed-responsive-nav.js"></script>
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/waypoints.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
//$('#contactpage').validate();
$('#contactpage').submit(function(){
var action = $(this).attr('action');
$.ajax({
type: "POST",
url: action,
data: {
name: $('#name').val(),
email: $('#email').val(),
subject: $('#subject').val(),
message: $('#message').val()
},
dataType: "json",
cache: false,
success: function (data) {
if(data.type == 'success') {
alert(data.text);
}
else {
alert(data.text);
}
}
});
/*$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
subject: $('#subject').val(),
message: $('#message').val()
},
function(data){
if(data.type == 'success') {
alert("Message sent successfully.");
}
else {
alert("An error occured.");
}
}
);*/
return false;
});
});
</script>
</body>
</html>
PHP:
<?php
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if(empty($name)) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Please Enter Your Name.'
));
die($output);
} else if(trim($email) == '') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'You Have Enter An Invalid E-mail Address, Try Again.'
));
die($output);
}
else if(!isEmail($email)) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'You Have Enter An Invalid E-mail Address, Try Again.'
));
die($output);
}
else if(empty($subject)) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Please Enter Your Mail Subject.'
));
die($output);
}
else if(empty($message)) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Please Enter Your Message.'
));
die($output);
}
else {
$fromMail = $email;
$toMail = "myemail#gmail.com";
$boundary = str_replace(" ", "", date('l jS \of F Y h i s A'));
$subjectMail = "Contact Form From $name | Examportal";
$body = "Name : $name <br/>
Email: $email <br/>
Message Title : $subject <br/>
Message : \n $message
";
$contentHtml = '
<div style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#333;">
<div style="color:#565656;">'.$body.'</div>
</div>
<div style="clear:both"></div>
';
$headersMail = '';
$headersMail .= 'From: ' ."noreply#emailexample.co.za\r\n" . 'Reply-To: ' . $fromMail . "\r\n";
$headersMail .= 'Return-Path: ' . $fromMail . "\r\n";
$headersMail .= 'MIME-Version: 1.0' . "\r\n";
$headersMail .= 'Content-Type: text/html; charset=ISO-8859-1' . "\r\n";
try {
if (mail($toMail, $subjectMail, $contentHtml, $headersMail)) {
$output = json_encode(array( //create JSON data
'type'=>'success',
'text' => 'Thank you for contacting us, we will get back to you real soon. :).'
));
die($output);
} else {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'An unknown error occuredx. Please try again later.'
));
die($output);
}
} catch(Exception $e) {
$msg = $e->getMessage();
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Error occur with message : '.$msg
));
die($output);
}
}
?>
Simplest and easiest way to validate any blank field is by adding required in your input HTML as below.
<form method="post" class="submitphoto_form" action="contact.php" id="contactpage">
<input type="text" class="form-control wpcf7-text" placeholder="Your name" name="name" id="name" required>
<input type="email" class="form-control wpcf7-email" placeholder="Email address" name="email" id="email" required>
<input type="text" class="form-control wpcf7-text" placeholder="Subject" name="subject" id="subject" required>
<textarea style="height:300px" class="form-control wpcf7-text" placeholder="What would you like to tell us" name="message" id="message" required></textarea>
<input type="submit" value="Submit" class="wpcf7-submit photo-submit" name="send" id="send">
</form>
Also note that your input email type should be "email" and not "mail".
Drawback of using PHP validation is that the user will have to re-enter all the fields.
Drawback of using JS validation is that if the user has disabled JS, then the validation will not work.
Benefit of using simple HTML validation is that it will work on all the browsers and will stop the form submission in case of any empty field and/or invalid email format.
With this approach, you are not required to validate using JS. It is pure HTML.
Hope this helps.
I have started to make a message box, where a user can send a message to me. When I run the code the boxes is working fine, but I never receive a mail, and I do not get any errors. Can anybody see if I am doing something totally wrong?
<?php
//set validation error flag as false
$error = false;
//check if form is submitted
if (isset($_POST['submit']))
{
$name = trim($_POST['txt_name']);
$fromemail = trim($_POST['txt_email']);
$subject = trim($_POST['txt_subject']);
$message = trim($_POST['txt_msg']);
//name can contain only alpha characters and space
if (!preg_match("/^[a-zA-Z ]+$/",$name))
{
$error = true;
$name_error = "Please Enter Valid Name";
}
if(!filter_var($fromemail,FILTER_VALIDATE_EMAIL))
{
$error = true;
$fromemail_error = "Please Enter Valid Email ID";
}
if(empty($subject))
{
$error = true;
$subject_error = "Please Enter Your Subject";
}
if(empty($message))
{
$error = true;
$message_error = "Please Enter Your Message";
}
if (!$error)
{
//send mail
$toemail = "test#stackoverflow.com";
$subject = "Enquiry from Visitor " . $name;
$body = "Here goes your Message Details: \n\n Name: $name \n From: $fromemail \n Message: \n $message";
$headers = "From: $fromemail\n";
$headers .= "Reply-To: $fromemail";
if (mail ($toemail, $subject, $body, $headers))
$alertmsg = '<div class="alert alert-success text-center">Message sent successfully. We will get back to you shortly!</div>';
else
$alertmsg = '<div class="alert alert-danger text-center">There is error in sending mail. Please try again later.</div>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 3 Contact Form Example</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" >
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 well">
<form role="form" class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactform">
<fieldset>
<legend>Bootstrap Contact Form</legend>
<div class="form-group">
<div class="col-md-12">
<label for="txt_name" class="control-label">Name</label>
</div>
<div class="col-md-12">
<input class="form-control" name="txt_name" placeholder="Your Full Name" type="text" value="<?php if($error) echo $name; ?>" />
<span class="text-danger"><?php if (isset($name_error)) echo $name_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="txt_email" class="control-label">Email ID</label>
</div>
<div class="col-md-12">
<input class="form-control" name="txt_email" placeholder="Your Email ID" type="text" value="<?php if($error) echo $fromemail; ?>" />
<span class="text-danger"><?php if (isset($fromemail_error)) echo $fromemail_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="txt_subject" class="control-label">Subject</label>
</div>
<div class="col-md-12">
<input class="form-control" name="txt_subject" placeholder="Your Subject" type="text" value="<?php if($error) echo $subject; ?>" />
<span class="text-danger"><?php if (isset($subject_error)) echo $subject_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="txt_msg" class="control-label">Message</label>
</div>
<div class="col-md-12">
<textarea class="form-control" name="txt_msg" rows="4" placeholder="Your Message"><?php if($error) echo $message; ?></textarea>
<span class="text-danger"><?php if (isset($message_error)) echo $message_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input name="submit" type="submit" class="btn btn-primary" value="Send" />
</div>
</div>
</fieldset>
</form>
<?php if (isset($alertmsg)) { echo $alertmsg; } ?>
</div>
</div>
</div>
</body>
</html>
Im trying to create a form to send me an email when the user fills all the fields, I followed a tutorial to put it together so whats there works, but I want to implement an option that allows people to pick other... Heres how it is:
I have a form that asks for your: Name, Email, Type and Message.
The type has 4 options: Feedback, Bug Report, Feature Request and other, I would love if when the other radio button is clicked then the text box HAS to have an input, so they cant just skip by pressing other, but if they pick something else that isnt other then I dont want them to have to type in the text box, but no matter what I try it either doesnt work at all or HAS to have an input in the text box even if I dont select the other radio button...
The problem is resolved, I request that this topic remains open so that others can continue to use this page, or incase I break something... Thanks Rasclatt, You were an amazing help :)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<link href="contact/css/contactForm.css" rel="stylesheet">
<title>Contact Us</title>
<?php error_reporting(0); ?>
<?php if(isset($_POST['Email'])): ?>
<?php
print_r($_POST);
// This is where you process the email and display the thank you page
$to = 'harryfelton12#gmail.com';
$subject = 'ALERT! Website Form Submission';
$message = 'Users Email: '.strip_tags($_POST['Email'])."\n";
$message .= 'Submitted Message: '.strip_tags($_POST['Comment'])."\n";
$message .= 'Message Type: '.strip_tags($_POST['Type'])."\n";
$headers = 'From: harrywebsite#form.com' . "\r\n" .
'Reply-To: '.strip_tags($_POST['Email']) . "\r\n";
// If the mail is successful, display thanks or display failed
?>
<?php if(mail($to, $subject, $message, $headers)): ?>
// Display the thank you page }
<div id="comments_form">
<h2 style="size:35px;">Thanks For Your Message!</h2>
<p style="font-size: 20px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">You Will Be Redirected Shortly!</p>
<p style="font-size: 15px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">Expect your message to be responded to within 2 working days</p>
<script type="text/javascript">
setTimeout('redirectPage()', 3000)
function redirectPage() {
location.href="index.html"
};
</script>
<?php else: ?>
<div id="comments_form">
<h2 style="size:35px;">Uh Oh! Your Message Could Not Be Sent</h2>
<p style="font-size: 20px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">An Unexpected Error Occured While Trying To Send Your Message</p>
<p style="font-size: 15px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">You Are Being Redirected To The Home Page</p>
<script type="text/javascript">
setTimeout('redirectPage()', 3000)
function redirectPage() {
location.href="index.html"
};
</script>
<?php endif ?>
</div>
<?php else: ?>
<form method="post" id="comments_form">
<div class="row">
<div class="label">
Your Name
</div>
<!--.label end-->
<div class="input">
<input type="text" id="fullname" class="detail" name="Name"
value="<?php echo isset($_POST['Name'])? $_POST['Name'] : ''; ?>" />
<?php if(in_array('Name', $validation)): ?>
<span class="error"><?php echo $error_messages['Name']; ?></span>
<?php endif; ?>
</div>
<!--.input end-->
<div class="context">
e.g. John Smith or Jane Doe
</div>
<!--end .context-->
</div>
<!--.row end-->
<div class="row">
<div class="label">
Your Email
</div>
<!--.label end-->
<div class="input">
<input type="text" id="email" class="detail" name="Email" value="<?php echo isset($_POST['Email'])? $_POST['Email'] : ''; ?>" />
<?php if(in_array('Email', $validation)): ?>
<span class="error"><?php echo $error_messages['Email']; ?></span>
<?php endif; ?>
</div>
<!--.input end-->
<div class="context">
We wont spam you! We only need this to reply to questions you might pose
</div>
<!--end .context-->
</div>
<!--.row end-->
<div class="row">
<div class="label">
Type Of Message
</div>
<!--.label end-->
<div class="input">
<input type="radio" name="Type" onChange="GetValue(this)" value="Feedback" checked="checked" />
Feedback <br />
<input type="radio" name="Type" onChange="GetValue(this)" value="Feature Request" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Feature Request')? 'checked="checked"' : ''; ?> />
Feature Request<br>
<input type="radio" name="Type" onChange="GetValue(this)" value="Bug Report" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Bug Report')? 'checked="checked"' : ''; ?> />
Bug Report<br>
<input type="radio" name="Type" onChange="GetValue(this)" value="Other" id="other" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Other')? 'checked="checked"' : ''; ?> />
Other<br />
<input type="text" style="display:none;" id="option" name="Type" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'option')? 'checked="checked"' : ''; ?> />
<?php if(in_array('Type', $validation)): ?>
<span class="error"> <?php echo $error_messages['Type']; ?> </span>
<?php endif; ?>
</div>
<!--.input end-->
<div class="context">
This is to help us better respond to your message
</div>
<!--end .context-->
</div>
<!--.row end-->
<div class="row">
<div class="label">
Your Message
</div>
<!--.label end-->
<div class="input2">
<textarea id="Comment" name="Comment" class="mess"><?php echo isset($_POST['Comment'])? $_POST['Comment'] : ''; ?></textarea>
<?php if(in_array('Comment', $validation)): ?>
<span class="error"><?php echo $error_messages['Comment']; ?></span>
<?php endif; ?>
</div>
<!--.input end-->
</div>
<!--.row end-->
<div class="submit">
<input type="submit" id="submit" name="Submit" value="Send Message" />
</div>
</form>
<?php endif; ?>
<script>
// This function just checks if the 'other' gets checked
function GetValue(ThisVal) {
var Writing = $(ThisVal).val();
// This just shows you what is happening via the feedback div
$('#feederback').html(Writing);
if (Writing == 'Other') {
// If other, disable the submit
$("#submit").prop("disabled", true);
// Fade in the message textarea
$('#option').fadeIn('fast');
// Check the message area to see if there is text in it already.
// If there is text enable the submit button
CheckVal();
} else {
// If not other, fade out the message
$('#option').fadeOut('fast');
// Enable the submit button
$('#submit').prop("disabled", false);
}
}
function CheckVal() {
var SetMess = $('#option').val();
$('#feedback').html(SetMess);
if (SetMess !== '') {
$('#submit').prop('disabled', false);
}
else {
$('#submit').prop('disabled', true);
}
}
// As one types, check that the message is not empty
$('#option').keyup(function () {
CheckVal();
});
// As one clicks into the field, see if it has content
$('#option').click(function () {
CheckVal();
});
$(document).ready(function() {
// validate form
$("#comments_form").validate({
// This will allow you to extend the validator functions
invalidHandler:
function(form, validator) {
// $("#get_online").val("CHECK");
},
rules: {
// For every named input that you want to validate,
// you create a little set of prefs
Name: {
required: true,
},
Email: {
required: true,
email: true
},
Type: { required: true },
Comment: { required: true },
},
messages: {
// Here are just the custom messages you can modify per field
Name: {
required: 'Please Enter Your Name',
},
Email: {
required: 'Please Enter An Email',
email: 'Email address not valid',
},
Type: { required: 'Please Select A Type' },
Comment: { required: 'Please Enter A Message'},
},
});
});
</script>
-Thanks in advance, harry
Ok so the validation is at the very bottom. I have it validating basic stuff. If you visit or google jQuery validation, you can see how to validate different fields. It's pretty easy. Make sure in your PHP that you filter ( strip_tags() ) the inputs so that you don't get hacked.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<link href="contact/css/contactForm.css" rel="stylesheet">
<title>Contact Us</title>
<?php error_reporting(0); ?>
<?php if(isset($_POST['Email'])): ?>
<?php
print_r($_POST);
// This is where you process the email and display the thank you page
$to = 'harryfelton12#gmail.com';
$subject = 'ALERT! Website Form Submission';
$message = 'Users Email: '.strip_tags($_POST['Email'])."\n";
$message .= 'Submitted Message: '.strip_tags($_POST['Comment'])."\n";
$message .= 'Message Type: ';
$message .= ($_POST['Type'] !== 'Option')? $_POST['Type']."\n": strip_tags($_POST['option'])."\n";
$headers = 'From: harrywebsite#form.com' . "\r\n" .
'Reply-To: '.strip_tags($_POST['Email']) . "\r\n";
// If the mail is successful, display thanks or display failed
?>
<?php if(mail($to, $subject, $message, $headers)): ?>
// Display the thank you page }
<div id="comments_form">
<h2 style="size:35px;">Thanks For Your Message!</h2>
<p style="font-size: 20px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">You Will Be Redirected Shortly!</p>
<p style="font-size: 15px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">Expect your message to be responded to within 2 working days</p>
<script type="text/javascript">
setTimeout('redirectPage()', 3000)
function redirectPage() {
location.href="index.html"
};
</script>
<?php else: ?>
<div id="comments_form">
<h2 style="size:35px;">Uh Oh! Your Message Could Not Be Sent</h2>
<p style="font-size: 20px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">An Unexpected Error Occured While Trying To Send Your Message</p>
<p style="font-size: 15px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">You Are Being Redirected To The Home Page</p>
<script type="text/javascript">
setTimeout('redirectPage()', 3000)
function redirectPage() {
location.href="index.html"
};
</script>
<?php endif ?>
</div>
<?php else: ?>
<form method="post" id="comments_form">
<div class="row">
<div class="label">
Your Name
</div>
<!--.label end-->
<div class="input">
<input type="text" id="fullname" class="detail" name="Name"
value="<?php echo isset($_POST['Name'])? $_POST['Name'] : ''; ?>" />
<?php if(in_array('Name', $validation)): ?>
<span class="error"><?php echo $error_messages['Name']; ?></span>
<?php endif; ?>
</div>
<!--.input end-->
<div class="context">
e.g. John Smith or Jane Doe
</div>
<!--end .context-->
</div>
<!--.row end-->
<div class="row">
<div class="label">
Your Email
</div>
<!--.label end-->
<div class="input">
<input type="text" id="email" class="detail" name="Email" value="<?php echo isset($_POST['Email'])? $_POST['Email'] : ''; ?>" />
<?php if(in_array('Email', $validation)): ?>
<span class="error"><?php echo $error_messages['Email']; ?></span>
<?php endif; ?>
</div>
<!--.input end-->
<div class="context">
We wont spam you! We only need this to reply to questions you might pose
</div>
<!--end .context-->
</div>
<!--.row end-->
<div class="row">
<div class="label">
Type Of Message
</div>
<!--.label end-->
<div class="input">
<input type="radio" name="Type" onChange="GetValue(this)" value="Feedback" checked="checked" />
Feedback <br />
<input type="radio" name="Type" onChange="GetValue(this)" value="Feature Request" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Feature Request')? 'checked="checked"' : ''; ?> />
Feature Request<br>
<input type="radio" name="Type" onChange="GetValue(this)" value="Bug Report" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Bug Report')? 'checked="checked"' : ''; ?> />
Bug Report<br>
<input type="radio" name="Type" onChange="GetValue(this)" value="Other" id="other" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Other')? 'checked="checked"' : ''; ?> />
Other<br />
<input type="text" style="display:none;" id="option" name="option" <?php echo (isset($_POST['option']))? $_POST['option']: ''; ?> />
<?php if(in_array('Type', $validation)): ?>
<span class="error"> <?php echo $error_messages['Type']; ?> </span>
<?php endif; ?>
</div>
<!--.input end-->
<div class="context">
This is to help us better respond to your message
</div>
<!--end .context-->
</div>
<!--.row end-->
<div class="row">
<div class="label">
Your Message
</div>
<!--.label end-->
<div class="input2">
<textarea id="Comment" name="Comment" class="mess"><?php echo isset($_POST['Comment'])? $_POST['Comment'] : ''; ?></textarea>
<?php if(in_array('Comment', $validation)): ?>
<span class="error"><?php echo $error_messages['Comment']; ?></span>
<?php endif; ?>
</div>
<!--.input end-->
</div>
<!--.row end-->
<div class="submit">
<input type="submit" id="submit" name="Submit" value="Send Message" />
</div>
</form>
<?php endif; ?>
<script>
// This function just checks if the 'other' gets checked
function GetValue(ThisVal) {
var Writing = $(ThisVal).val();
// This just shows you what is happening via the feedback div
$('#feederback').html(Writing);
if (Writing == 'Other') {
// If other, disable the submit
$("#submit").prop("disabled", true);
// Fade in the message textarea
$('#option').fadeIn('fast');
// Check the message area to see if there is text in it already.
// If there is text enable the submit button
CheckVal();
} else {
// If not other, fade out the message
$('#option').fadeOut('fast');
// Enable the submit button
$('#submit').prop("disabled", false);
}
}
function CheckVal() {
var SetMess = $('#option').val();
$('#feedback').html(SetMess);
if (SetMess !== '') {
$('#submit').prop('disabled', false);
}
else {
$('#submit').prop('disabled', true);
}
}
// As one types, check that the message is not empty
$('#option').keyup(function () {
CheckVal();
});
// As one clicks into the field, see if it has content
$('#option').click(function () {
CheckVal();
});
$(document).ready(function() {
// validate form
$("#comments_form").validate({
// This will allow you to extend the validator functions
invalidHandler:
function(form, validator) {
// $("#get_online").val("CHECK");
},
rules: {
// For every named input that you want to validate,
// you create a little set of prefs
Name: {
required: true,
},
Email: {
required: true,
email: true
},
Type: { required: true },
Comment: { required: true },
},
messages: {
// Here are just the custom messages you can modify per field
Name: {
required: 'Please Enter Your Name',
},
Email: {
required: 'Please Enter An Email',
email: 'Email address not valid',
},
Type: { required: 'Please Select A Type' },
Comment: { required: 'Please Enter A Message'},
},
});
});
</script>
i have a form with input for name and e-mail. I would like to have a dedicated error-message for each input - fx
if no name is written it will say "please write your name!"
and if the e-mail is missing or not valid it echoes "wrong mail - try again!"
At the moment I have only 1 error-message that will echo for both situations.
How can i assign an dedicated error-message for each of the inputs?
Heres the code:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = '##gmail.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<article class="kontakt">
<?php if($_POST['contactname'] != '') { //echo when a name was entered ?>
<!--<p> Hello </p>-->
<?php $name = strip_tags(trim($_POST['contactname']));
echo $name;
} ?>
</article>
<article class="kontakt">
<?php if(isset($hasError)) { // THIS PART IS ECHOED IN BOTH SITUATIONS - should only apply for error in e-mail?>
<p class="error"> Your mail is <span style="color: orange"> not correct</span> - try again! </p>
<?php } ?>
<?php if($_POST['email'] != '') { // echo when a valid mail was entered ?>
<p> Hello </p>
<?php $name = strip_tags(trim($_POST['email']));
echo $email;
} ?>
</article>
<article class="kontakt">
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p> Your message is sent !</p>
<?php } ?>
</article>
}
?>
try something like:
if(trim($_POST['contactname']) == '') {
$hasError['contactname'] = 'Please enter a contact name!';
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError['email'] = 'Please enter email!';
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError['validemail'] = 'Please enter valid email';
} else {
$email = trim($_POST['email']);
}
and this to display errors:
if(isset($hasError)){
echo '<ul>';
foreach($hasError as $error){
echo '<li>'.$error.'</li>';
}
echo '</ul>';
}
and this to keep old values upon error
<div class="right_wrap">
<div class="header"> <h5><span style="color: white"> mail </span></h5> </div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<article class="kontakt">
<label for="name"> Dit navn </label>
<input type="text" name="contactname" id="contactname" value="<?php echo $_POST['contactname']; ?>" class="" />
</article>
<article class="kontakt">
<label for="email"> Din mail </label>
<input type="text" name="email" id="email" value="<?php echo $_POST['email']; ?>" class="required email" />
</article>
<article class="kontakt" style="height: auto">
<label for="message"> Din besked </label>
<textarea rows="5" cols="50" name="message" class="required"><?php echo $_POST['message']; ?></textarea>
</article>
<article class="kontakt">
<input type="submit" value="Send besked" name="submit" class="button"/>
</article>
</form>
</div> <!--end of right_wrap -->
You treat each input with individual code that means you don't have much data-structure here.
Normally some kind of model for inputs as well as associated errors and values is helpful to get things done with forms.
A lightweight entry that normally works pretty well with individual PHP scripts is HTML_QuickForm2.
It does take care of individual error messages as well. You naturally can write that your own and luckily it is free software so you are allowed to study the code and learn from it.
Heres the actual form - some danish words in it. Whatever errors / messages will be output in a left wrap div - so cant be placed inside the actual form.
<div class="right_wrap">
<div class="header"> <h5><span style="color: white"> mail </span></h5> </div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<article class="kontakt">
<label for="name"> Dit navn </label>
<input type="text" name="contactname" id="contactname" value="" class="" />
</article>
<article class="kontakt">
<label for="email"> Din mail </label>
<input type="text" name="email" id="email" value="" class="required email" />
</article>
<article class="kontakt" style="height: auto">
<label for="message"> Din besked </label>
<textarea rows="5" cols="50" name="message" class="required"></textarea>
</article>
<article class="kontakt">
<input type="submit" value="Send besked" name="submit" class="button"/>
</article>
</form>
</div> <!--end of right_wrap -->