Why does email go through if Recaptcha is not checked? - php

I have been trying my very hard to have recaptcha verify a user and not send the email without them being verified. I have tried everything I can possibly think of, but the email goes out from my contact form even if the checkbox is blank. My form still checks if the form's fields are empty or if a valid email address is entered, but I never get warned that recaptcha is not solved if the checkbox isn't touched. I tried just about every tutorial I can think of and even links from within the Stackoverflow community. Many thanks in advance.
FORM
<form action="mail.php" method="POST">
<h1>Contact</h1>
<input type="text" placeholder="First name" id="firstname" maxlength="50">
<br>
<input type="text" placeholder="Last name" id="lastname" maxlength="50">
<br>
<input type="text" placeholder="Email" id="email" maxlength="50">
<br>
<input type="text" placeholder="Subject" id="subject" maxlength="50">
<br>
<textarea id="message" name="message" placeholder="Message..." maxlength="120"></textarea>
<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="sitekey"></div>
<input type="submit" value="Submit" id="submit_button">
<br>
<p class="form-message"></p>
<?php if (isset($_GET['CaptchaFail'])){?>
<div class="form-error">You have not proven you are not a robot!</div>
<?php }?>
<script>
$(document).ready(function(){
$("form").submit(function (event) {
event.preventDefault();
var first = $("#firstname").val();
var last = $("#lastname").val();
var subject = $("#subject").val();
var email = $("#email").val();
var message = $("#message").val();
var submit = $("#submit_button").val();
$(".form-message").load("mail.php", {
first: first,
last: last,
subject: subject,
email: email,
message: message,
submit: submit
});
});
});
</script>
SERVER SIDE FIELD VALIDATION
<?php
if (isset($_POST['submit'])){
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$submit = $_POST['submit'];
$errorEmpty = false;
$errorEmail = false;
if (empty($first) || empty($last) || empty($email) || empty($subject) || empty($message)){
echo "<span class='form-error'>Fill in all fields!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>Write a valid email address!</span>";
$errorEmail = true;
}
else{
if(isset($_POST['submit'])){
$first = $_POST['first'];
$last = $_POST['last'];
$emailFrom = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$success = "<span class='form-success'>Message Success!</span>";
$emailTo = "ovalenzuela#itsmilvus.com";
$headers = "From: ".$emailFrom;
$txt = "You have received an email from ".$first . ' '.$last."\n\n".$message;
mail($emailTo, $subject, $txt, $headers);
echo "<span class='form-success'>$success</span>";
}
}
}
elseif (isset($_POST['submit'])){
}
else{
echo "There was an error!";
}
?>
<script>
var thanks = '<div>Thank you for you message!</div><br><Return to main page';
$("#firstname, #lastname, #email, #subject, #message").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
if (errorEmpty == true){
$("#firstname, #lastname, #email, #subject, #message").addClass("input-error");
}
if (errorEmail == true){
$("#email").addClass("input-error");
}
if (errorEmpty == false && errorEmail == false){
$("#firstname, #lastname, #email, #subject, #message").val("");
$("#contact-form").html(thanks).addClass("form-success");
}
</script>
RECAPTCHA VALIDATION (This is in the contact.php file.)
<?php
if (isset($_POST['submit'])){
$url = "https://www.google.com/recaptcha/api/siteverify";
$privatekey = "secretkey";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data-success == true){
header('Location:contact.php?CaptchaPass==true');
}
else{
header('Location:contact.php?CaptchaFail==true');
}
}
?>

After reading all of the comments things started to make more sense. Ended up validating the recaptcha from the front end and then wrote the server side code to make it happen.
Here is the PHP logic I used to fix the issue that I got when recpatcha was left blank:
if (empty($first) || empty($last) || empty($email) || empty($subject) || empty($message)) {
echo "<br><span class='form-error'>Fill in all fields!</span>";
$errorEmpty = true;
} // Validate if an email is entered
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>Write a valid email address!</span>";
$errorEmail = true;
}
elseif (isset($data->success) && $data->success==true) {
$rescapStatus = true;
}
elseif (!empty($_POST['recaptcha'])) {
// echo('<p class="form-error"> Please set recaptcha variable.</p>');
$recapBox = true;
}
else {
$emailTo = "ovalenzuela#itsmilvus.com";
$headers = "From: " . $emailFrom;
$txt = "You have received an email from " . $first . ' ' . $last . "\n\n" . $message;
mail($emailTo, $subject, $txt, $headers);
}
}
else{
echo "There was an error!";
}
?>
<script>
var thanks = '<div>Thank you for you message!</div><br><Return to main page';
$("#firstname, #lastname, #email, #subject, #message").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
var recapStatus = "<?php echo $recapStatus; ?>";
var recapBox = "<?php echo $recapBox; ?>";
if (errorEmpty == true){
$("#firstname, #lastname, #email, #subject, #message").addClass("input-error");
}
if (errorEmail == true){
$("#email").addClass("input-error");
}
if (errorEmpty == false && errorEmail == false && recapBox == false){
$("#firstname, #lastname, #email, #subject, #message").val("");
$("#contact-form").html(thanks).addClass("form-success");
}
</script>

Related

PHP Multiple Validations

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.

How to make this php script send in ajax instead

i have a contact form and it sends just with php atm, i want to send it with ajax?
whats the easiest way?
<?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 that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//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']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!$hasError) {
$emailTo = '123#gmail.com'; // Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
if(wp_mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
}else{
echo '<p class="alert-message error">Error sending mail.</p>';
}
}
}
?>
Please maybe give pointers on also improving the send function.
Any help really appreciated.
if you need to see the form let me know and i will edit and put it in
You can modify your code as follows.
Below is a stand-alone example (untested) of exactly what you requested.
Simply copy/paste the two code blocks into two files:
contacttest.php (or whatever you wish to call it)
yourphpprocessor.php (if change name, must also change it in AJAX code block)
Note that:
1. Each form element now has an ID attr
2. <form> functionality is no longer used at all, and is in fact prevented via e.preventDefault()
HTML: contacttest.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
$(document).ready(function() {
//If you want the output from php side in a lightbox...
$('#alertmsg').dialog({
autoOpen: false,
modal: true,
width: 400,
buttons: {
Thanks: function() {
$(this).dialog('close');
}
}
});
$('#contactform').submit(function(e) {
e.preventDefault();
var frm = $('#cname').val();
var eml = $('#cemail').val();
var sub = $('#subj').val();
var msg = $('#msg').val();
//validation goes here, for eg.
if (frm == '' || eml==''){
alert('All fields must be completed');
return false;
}
$.ajax({
type: "POST",
url: "yourphpprocessor.php",
data: 'f=' +frm+ '&e=' +eml+ '&s=' +sub+ '&m=' +msg,
success: function(recd) {
$('#alertmsg').html(recd);
$('#alertmsg').dialog('open'); //Uses lightbox to display message
}
});
}); //END AJAX
}); //END $(document).ready()
</script>
</head>
<body>
<form id="contactform" action="" method="POST">
From: <input type="text" name="contactname" id="cname"><br />
Email: <input type="text" name="email" id="cemail"><br />
Subject: <input type="text" name="subject" id="subj"><br />
Message: <textarea name="message" id="msg"></textarea><br /><br />
<input type="submit" id="mysubmit" value="Submit">
</form>
<div id="alertmsg"></div>
</body>
</html>
PHP Side: yourphpprocessor.php
<?php
$name = $_POST['f'];
$email = $_POST['e'];
$subject = $_POST['s'];
$comments = $_POST['m'];
$emailTo = '123#gmail.com'; // Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
if(wp_mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
}else{
echo '<p class="alert-message error">Error sending mail.</p>';
}
?>
You need to do this on the client side
Just use this plugin http://jquery.malsup.com/form/

Validation does not work with PHP

I am having problem to see the problem with a pre-scripted template.
There are 3 files as follows,
/contact.php
/forms/contact.php
/js/forms.js
So when a visitor fills up the contact.php in root directory it redirects to /forms/contact.php and forms.js checks the form and if there is no problem sends an email.
Here is my /contact.php which includes the form,
<form id="contactform" method="post" action="forms/contact.php">
<div class="divide10"></div>
<input id="name" name="name" value="Your Name" type="text" class="prepared-input">
<div class="divide15"></div>
<input id="email" name="email" value="Your Email" type="text" class="prepared-input">
<div class="divide15"></div>
<textarea id="contactmessage" name="message" rows="3" class="prepared-input">Your Message</textarea>
<div class="divide15"></div>
<input type="submit" id="From_Comment_Go" value="Send Message " class="btn maincolor small">
<span class="errormessage hiddenatstart">Error! Please correct marked fields.</span>
<span class="successmessage hiddenatstart">Message send successfully!</span>
<span class="sendingmessage hiddenatstart">Sending...</span>
</form>
Here is my /forms/contact.php
<?php
$to = 'example#mail.com';
//Language Options
$contact_labelmailhead = 'Contact Form Email';
$contact_labelmailsubject = 'Contact Form Email from';
$contact_labelname = 'Name';
$contact_labelemail = 'Email';
$contact_labelmessage = 'Message';
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = str_replace(chr(10), "<br>", $_POST['message']);
$body = "<html><head><title>$contact_labelmailhead</title></head><body><br>";
$body .= "$contact_labelname: <b>" . $name . "</b><br>";
$body .= "$contact_labelemail <b>" . $email . "</b><br>";
$body .= "$contact_labelmessage:<br><hr><br><b>" . $message . "</b><br>";
$body .= "<br></body></html>";
$subject = $contact_labelmailsubject.' ' . $name;
$header = "From: $email\n" . "MIME-Version: 1.0\n" . "Content-type: text/html; charset=utf-8\n";
mail($to, $subject, $body, $header);
?>
and lastly forms.js is here,
jQuery(document).ready(function() {
/* Contact Form */
if(jQuery('#contactform').length != 0){
addForm('#contactform');
}
/* Quick Contact */
if(jQuery('#quickcontact').length != 0){
addForm('#quickcontact');
}
/* Blog Comments */
if(jQuery('#replyform').length != 0){
addForm('#replyform');
}
});
function addForm(formtype) {
var formid = jQuery(formtype);
var emailsend = false;
formid.find("input[type=submit]").click(sendemail);
function validator() {
var emailcheck = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var othercheck = /.{4}/;
var noerror = true;
formid.find(".requiredfield").each(function () {
var fieldname = jQuery(this).attr('name');
var value = jQuery(this).val();
if(value == "Name *" || value == "Email *" || value == "Message *"){
value = "";
}
if(fieldname == "email"){
if (!emailcheck.test(value)) {
jQuery(this).addClass("formerror");
noerror = false;
} else {
jQuery(this).removeClass("formerror");
}
}else{
if (!othercheck.test(value)) {
jQuery(this).addClass("formerror");
noerror = false;
} else {
jQuery(this).removeClass("formerror");
}
}
})
if(!noerror){
formid.find(".errormessage").fadeIn();
}
return noerror;
}
function resetform() {
formid.find("input").each(function () {
if(!jQuery(this).hasClass("button")) jQuery(this).val("");
})
formid.find("textarea").val("");
emailsend = false;
}
function sendemail() {
formid.find(".successmessage").hide();
var phpfile = "";
if(formtype=="#contactform"){
phpfile = "forms/contact.php";
}else if(formtype.lastIndexOf("c_")){
phpfile = "forms/quickcontact.php";
}else{
phpfile = "";
}
if (validator()) {
if(!emailsend){
emailsend = true;
formid.find(".errormessage").hide();
formid.find(".sendingmessage").show();
jQuery.post(phpfile, formid.serialize(), function() {
formid.find(".sendingmessage").hide();
formid.find(".successmessage").fadeIn();
if(!formtype.lastIndexOf("c_"))resetform();
});
}
}
return false
}
}
So, leaving the form sends Values :S and does not check anything. Shall I try to fix this or try to implement something else? I am not that into jQuery and cannot say if there is something wrong with validation script.
Some advice would be great!
Thank you!
There are errors on .js syntax, this could stop some js code from being called. First of all, fix these errors in js like this:
formid.find("input").each(function ()
{
if(!jQuery(this).hasClass("button")) jQuery(this).val("");
})//this is missing a ;
After that you can think properly on post method like Kevin Schmid said..
The validator function check each input with ".requiredfield" class.
Sample Code :
formid.find(".requiredfield").each(function () {

PHP, Not able to send Emails

I would like to have a contact form on my that requires the *fullname, *email address, and *subject and *message. I followed a tutorial to develop my form but for some reason it is not sending my test message.
I'm not experienced enough with PHP to figure out what I am doing wrong, so I am hoping to get suggestions on how to resolve this issue. All questions, suggestions, and possible solutions are welcome. Thanks.
contact form php:
Code:
<?php
// EDIT THE FOLLOWING LINE BELOW AS REQUIRED
$send_email_to = "jb#me.com";
function send_email($name,$email,$email_subject,$email_message)
{
global $send_email_to;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>Message = </strong>".$email_message."<br>";
#mail($send_email_to, $email_subject, $message,$headers);
return true;
}
function validate($name,$email,$message,$subject)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['message_msg'] = '';
$return_array['subject'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'enter valid email.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'enter valid name.';
}
}
if($subject == '')
{
$return_array['success'] = '0';
$return_array['subject_msg'] = 'subject is required';
}
if($message == '')
{
$return_array['success'] = '0';
$return_array['message_msg'] = 'message is required';
}
else
{
if (strlen($message) < 2) {
$return_array['success'] = '0';
$return_array['message_msg'] = 'enter valid message.';
}
}
return $return_array;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$return_array = validate($name,$email,$message,$subject);
if($return_array['success'] == '1')
{
send_email($name,$email,$subject,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
Contact Form HTML:
Code:
<fieldset id="contact_form">
<div id="msgs"> </div>
<form id="cform" name="cform" method="post" action="">
<input type="text" id="name" name="name" value="Full Name*" onfocus="if(this.value == 'Full Name*') this.value = ''"
onblur="if(this.value == '') this.value = 'Full Name*'" />
<input type="text" id="email" name="email" value="Email Address*" onfocus="if(this.value == 'Email Address*') this.value = ''"
onblur="if(this.value == '') this.value = 'Email Address*'" />
<input type="text" id="subject" name="subject" value="Subject*" onfocus="if(this.value == 'Subject*') this.value = ''"
onblur="if(this.value == '') this.value = 'Subject*'" />
<textarea id="msg" name="msg" onfocus="if(this.value == 'Your Message*') this.value = ''"
onblur="if(this.value == '') this.value = 'Your Message*'">Your Message*</textarea>
<button id="submit" class="button"> Send Message</button>
</form>
</fieldset>
Your form's action isn't set to anything. You'll need to point it at the script you have there that sends the email.
Ie:
<form id.. name.. method.. action="/handle_post.php">
Set the correct action and then try it should work..
if it still does not work test it with curl utility to see if ur script is fine..
One more mistake that i saw was that ur text area form name is msg while on server ur expecting ur post request it have message. That wont work..
If u still face problem then we wd debug further :)
First you need to set action to some script that will handle $_POST inputs (contactform.php) or $_SERVER['PHP_SELF'] for the same file.
Second you should send data by input type=submit not button.

Jquery PHP form submit - How to get form inputs to display?

I have a contact form > www.bgv.co.za/testspace/contact_3.php
it uses jquery validate and PHP. I have some add/ remove class bits to hide or reveal a Thank you title and some php if isset to echo back the successful form submission inputs.
My problem is that on submission you see the thank you page but the div> sadhu is not showing the data that the user input... infact its not displaying as a div - please help
Here is my Jquery:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function(form) {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
form.submit();
}
});
});
Here is my PHP:
$subject = "Website Contact Form Enquiry";
//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']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //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;
}
}
And here is my FORM:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform" >
<div class="_required"><p class="label_left">Name*</p><input type="text" size="50" name="contactname" id="contactname" value="" class="required" /></div><br/><br/>
<div class="_required"><p class="label_left">E-mail address*</p><input type="text" size="50" name="email" id="email" value="" class="required email" /></div><br/><br/>
<p class="label_left">Message</p><textarea rows="5" cols="50" name="message" id="message" class="required"></textarea><br/>
<input type="submit" value="submit" name="submit" id="submit" />
</form>
The <div id='sadhu'> is not defined anywhere. You're appending it to #content with Javascript code, but it doesn't exist.
$("#content").append('#sadhu');
You might want something like
$("#content").append("<div id='sadhu'>stuff in here...</div>");
You have placed the form entries into something with the id out. If that stuff should also be in <div id='sadhu'>, then you can just place the .html() of out into it:
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
$("#content").append("<div id='sadhu'>" + $("#out").html() + "</div>");

Categories