I am trying to setup a fairly straight forward email form that will show a div if the email is successfully submitted and error messages when a field is not properly filled out. Currently, the Jquery side of things work, but it will not send the email. I am new to PHP, so I am not sure how to troubleshoot the PHP side of things, but all the code looks like it is correct.
HTML:
<form id="contactForm" >
<fieldset class="half float-left left">
<div class="overlay-field">
<label for="firstname" class="float-left">First Name</label>
<input id="firstname" type="text" name="firstname" >
<span id="errorFirstName" class="formError"></span>
</div>
<div class="overlay-field" data-error="">
<label for="telephone" class="float-left">Telephone</label>
<input id="telephone" type="text" name="telephone" >
<span id="errorPhone" class="formError"></span>
</div>
</fieldset>
<fieldset class="half float-right right">
<div class="overlay-field">
<label for="lastname" class="float-left">Last Name</label>
<input id="lastname" type="text" name="lastname" >
<span id="errorLastName" class="formError"></span>
</div>
div class="overlay-field" data-error="">
<label for="email" class="float-left">Email Address</label>
<input id="email" type="text" name="email" >
<span id="errorEmail" class="formError"></span>
</div>
</fieldset>
<label for="message" class="textarea-label float-left">Your Message</label>
<textarea id="message" value="Scope of Work" class="description" name="message" ></textarea>
<span id="errorMessage" class="formError"></span>
<div class="message_area">
<p class="success_message">WOOT WOOT! You're message has been sent! We will get back to you shortly.</p>
<p class="error_message">Something went wrong. Please make sure all fields are filled in properly.</p>
</div>
<button type="submit" id="submit" class="bttn bttn-4 bttn-4a">Send Message</button>
</form>
JQUERY:
$(document).ready(function() {
$('#contactForm #submit').click(function() {
$('#contactForm .formError').html('');
var isFocus=0;
var isError=0;
var firstname=$('#contactForm #firstname').val();
var lastname=$('#contactForm #lastname').val();
var email=$('#contactForm #email').val();
var telephone=$('#contactForm #telephone').val();
var message=$('#contactForm #message').val();
if(firstname=='') {
$('#contactForm #errorFirstName').html('This is a required field.');
$('#contactForm #firstname').focus();
isFocus=1;
isError=1;
}
if(lastname=='') {
$('#contactForm #errorLastName').html('This is a required field.');
$('#contactForm #lastname').focus();
isFocus=1;
isError=1;
}
if(telephone=='') {
$('#contactForm #errorPhone').html('This is a required field.');
$('#contactForm #telephone').focus();
isFocus=1;
isError=1;
}
if(email=='') {
$('#contactForm #errorEmail').html('This is a required field.');
if(isFocus==0) {
$('#contactForm #email').focus();
isFocus=1;
}
isError=1;
} else {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(email)==false) {
$('#contactForm #errorEmail').html('Invalid email address.');
if(isFocus==0) {
$('#contactForm #email').focus();
isFocus=1;
}
isError=1;
}
}
if(message=='') {
$('#contactForm #errorMessage').html('This is a required field.');
$('#contactForm #message').focus();
isFocus=1;
isError=1;
}
// Terminate the script if an error is found
if(isError==1) {
return false;
}
$.ajaxSetup ({
cache: false
});
$.ajax({
type: "POST",
url: "/wp-content/themes/apds/contact-ajax.php",
data: $("#contactForm").serializeArray(),
success: function(msg) {
$(".success_message").fadeIn().delay(5000).fadeOut();
$("#contactForm")[0].reset();
$('#contactForm #submit').removeAttr("disabled");
},
error: function(ob,errStr) {
$('#contactForm #submit').removeAttr("disabled");
}
});
return false;
});
});
PHP
<?php
if(empty($_POST['firstname']) ||
empty($_POST['lastname']) ||
empty($_POST['telephone']) ||
empty($_POST['email']) ||
empty($_POST['message'])) {
die('Error: Missing variables');
}
$email_subject = "Your email subject line";
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$telephone=$_POST['telephone'];
$message=$_POST['message'];
$to='my#email.com';
$headers = 'From: '.$email."\r\n" .
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
$email_subject = $email_subject;
$body='You have got a new message from the contact form on your website.'."\n\n";
$body.='First Name: '.$firstname."\n";
$body.='Last Name: '.$lastname."\n";
$body.='Email: '.$email."\n";
$body.='Telephone: '.$telephone."\n";
$body.='Message: '."\n".$message."\n";
if(mail($to, $email_subject, $body, $headers)) {
die('Mail sent');
} else {
die('Error: Mail failed');
}
?>
Related
I have a contact form that works perfectly when it is on a server. But I'm trying to keep only the handler.php on the server and rest of files offline. It's been sending emails so far nicely. The only problem is, it doesn't show the success message after the email has been successfully sent, which was not a problem when all the files were online.
So I am trying to make a html-file with the form in it that I can ghive people to open it locally in their browsers. Then, after they hit submit the data will be sent to your php-site on a online-server.
What should I update to get the success or error message form the emailing process? Thanks in advance for your suggestions.
The form-scripts.js:
$("#contactForm").validator().on("submit", function(event) {
if (event.isDefaultPrevented()) {
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
event.preventDefault();
submitForm();
}
});
function submitForm() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "http://example.com/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success: function(text) {
if (text == "success") {
formSuccess();
} else {
formError();
submitMSG(false, text);
}
}
});
}
function formSuccess() {
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError() {
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
$(this).removeClass();
});
}
function submitMSG(valid, msg) {
if (valid) {
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
This is the form-process.php which is on a server:
<?php
$errorMSG = "";
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$EmailTo = "example#gmail.com";
$Subject = "New Message Received";
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
$success = mail($EmailTo, $Subject, $Body, "From:" . $email);
// redirect to success page
if ($success && $errorMSG == "") {
echo "success";
} else {
if ($errorMSG == "") {
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
And here is the form:
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" required data-error="NEW ERROR MESSAGE">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="h4 ">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="btn btn-success btn-lg pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
I have that PHP, jQuery, and AJAX Powered Contact Form Bootstrap
It use Form Validator.
I want to add Security Question Input into that form (like here), to prove the user is human.
Not something complicated. Question like that:
Question: What is the capital city of New York?
Answer: New York
If the user write "new york" and submit, the form will send.
Here is the code:
Here is the index.html HTML Markup code:
<form role="form" id="contactForm" class="contact-form" data-toggle="validator" class="shake">
<div class="form-group">
<div class="controls">
<input type="text" id="name" class="form-control" placeholder="Name" required data-error="Please enter your name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" class="email form-control" id="email" placeholder="Email" required data-error="Please enter your email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" id="msg_subject" class="form-control" placeholder="Subject" required data-error="Please enter your message subject">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<textarea id="message" rows="7" placeholder="Massage" class="form-control" required data-error="Write your message"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<button type="submit" id="submit" class="btn btn-effect"><i class="fa fa-check"></i> Send Message</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
Here is the contact-form-script.js code:
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var msg_subject = $("#msg_subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "assets/php/form-process.php",
data: "name=" + name + "&email=" + email + "&msg_subject=" + msg_subject + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
Here's the form-process.php
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Subject is required ";
} else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "your#email.com";
$Subject = "New Message";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Subject: ";
$Body .= $msg_subject;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
What do i need to add in the php file (or in the js file as well) so i can prove the user is human?
Problems Solved !
Juste replace :
<div class='form-group'>
<div id="google" class="g-recaptcha" data-sitekey="MYPUBLICKEY" data-callback="callback" required data-error="Validate recaptcha"></div>
<div class="help-block with-errors"></div>
</div>
With this :
<div id="recaptcha" class="g-recaptcha" data-sitekey="MYPUBLICKEY"></div>
<div class="help-block with-errors">
<span class="msg-error error"></span>
</div>
And add this js script in new file :
$( '#submit' ).click(function(){
var $captcha = $( '#recaptcha' ),
response = grecaptcha.getResponse();
if (response.length === 0) {
$( '.msg-error').text( "reCAPTCHA is mandatory" );
if( !$captcha.hasClass( "error" ) ){
$captcha.addClass( "error" );
}
} else {
$( '.msg-error' ).text('');
$captcha.removeClass( "error" );
alert( 'reCAPTCHA marked' );
}
})
I would like to add a reCaptcha V2 to my little form contact.
This form use PHP & Ajax to check if all fields aren't empty.
If a field is missing a message appear below this field to inform user.
When all fields are complete ajax send email without page reload.
I would like to do the same with a reCAPTCHA. I've alreay read Official google documentation but it's a little hard for me. If I understood correctly I have to use my private key to check g-recaptcha-response. I dunno how to manipulate token to show message if user aren't complete reCaptcha like for the others fields.
Online exemple :
http://sosmooth.fr/form5/
All files in rar folder :
http://sosmooth.fr/form5.rar
Js File :
$("#contactForm").validator().on("submit", function(event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly ?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var msg_subject = $("#msg_subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "assets/php/form-process.php",
data: "name=" + name + "&email=" + email + "&msg_subject=" + msg_subject + "&message=" + message,
success: function(text) {
if (text == "success") {
formSuccess();
} else {
formError();
submitMSG(false, text);
}
}
});
}
function formSuccess() {
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError() {
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
$(this).removeClass();
});
}
function submitMSG(valid, msg) {
if (valid) {
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
HTML File :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="assets/css/animate.css" media="screen">
</head>
<body>
<section id="content">
<div class="container">
<div class="row">
<div class="col-md-9">
<h2>Contact Form</h2>
<!-- Start Contact Form -->
<form role="form" id="contactForm" class="contact-form" data-toggle="validator" class="shake">
<div class="form-group">
<div class="controls">
<input type="text" id="name" class="form-control" placeholder="Name" required data-error="Please enter your name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" class="email form-control" id="email" placeholder="Email" required data-error="Please enter your email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" id="msg_subject" class="form-control" placeholder="Subject" required data-error="Please enter your message subject">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<textarea id="message" rows="7" placeholder="Massage" class="form-control" required data-error="Write your message"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class='form-group'>
<div id="google" class="g-recaptcha" data-sitekey="MYPUBLICKEY" data-callback="callback" required data-error="Validate recaptcha"></div>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="submit" class="btn btn-success"></i> Send Message</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
</section>
<!-- Main JS -->
<script type="text/javascript" src="assets/js/jquery-min.js"></script>
<script type="text/javascript" src="assets/js/form-validator.min.js"></script>
<script type="text/javascript" src="assets/js/contact-form-script.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
</html>
PHP File :
<?php
$privatekey = "MYPRIVATEKEY"
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Subject is required";
} else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required";
} else {
$message = $_POST["message"];
}
$EmailTo = "john#doe.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body.= nl2br(stripslashes($name));
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Subject: ";
$Body .= nl2br(utf8_decode(stripslashes($msg_subject)));
$Body .= "\n";
$Body .= "Message: ";
$Body .= nl2br(utf8_decode(stripslashes($message)));
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
I want to add Google reCaptcha in this form I tried all things but all in vain.. What I need to do to make form successfully submitted.. and also make reCaptcha a required field using Ajax form submission...
HTML:-
<form id="contact-form" class="uk-form">
<fieldset>
<label>Name <em>*</em></label>
<input type="text" name="name" class="textfield" id="name" value="" />
<label>E-mail <em>*</em></label>
<input type="email" name="email" class="textfield" id="email" value="" />
<label>Services <em>*</em></label>
<input type="text" name="subject" class="textfield" id="subject" value="" />
<label>Message <em>*</em></label>
<textarea name="message" id="message" class="textarea" cols="2" rows="6"></textarea>
<div class="clearfix">
<div class="g-recaptcha" data-sitekey="My_Site_Key"></div>
</div>
<label> </label>
<button type="submit" name="submit" class="uk-button uk-button-small idz-button-blue" id="buttonsend">Submit</button>
<span class="loading" style="display: none;">Please wait..</span>
</fieldset>
</form>
JS:-
$('#buttonsend').click( function() {
var name = $('#name').val();
var subject = $('#subject').val();
var email = $('#email').val();
var message = $('#message').val();
$('.loading').fadeIn('fast');
if (name != "" && subject != "" && email != "" && message != "")
{
$.ajax(
{
url: './contact-us.php',
type: 'POST',
data: "name=" + name + "&subject=" + subject + "&email=" + email + "&message=" + message,
success: function(result)
{
$('.loading').fadeOut('fast');
if(result == "email_error") {
$('#email').css({"background":"#FFFCFC","border":"1px solid #ffadad"}).next('.require').text(' !');
} else {
$('#name, #subject, #email, #message').val("","Name","Subject","Email","Message");
$('<div class="uk-alert uk-alert-success uk-text-center uk-margin-medium-bottom" data-uk-alert><p>Your message has been sent successfully. Thank you!</p></div>').insertBefore('#contact-form');
$('.uk-alert').fadeOut(5000, function(){ $(this).remove(); });
}
}
}
);
return false;
}
else
{
$('.loading').fadeOut('fast');
if( name == "","Name") $('#name').css({"background":"#FFFCFC","border":"1px solid #ffadad"});
if(subject == "","Subject") $('#subject').css({"background":"#FFFCFC","border":"1px solid #ffadad"});
if(email == "","Email" ) $('#email').css({"background":"#FFFCFC","border":"1px solid #ffadad"});
if(message == "","Message") $('#message').css({"background":"#FFFCFC","border":"1px solid #ffadad"});
return false;
}
});
$('#name, #subject, #email,#message').focus(function(){
$(this).css({"border":"none","background":"#fafafa","border":"1px solid #ccc"});
});
PHP:-
$to = "xyz#mydomain.com";
$subject = "Contact Inquiry";
$name = $_POST['name'];
$email = $_POST['email'];
$services = $_POST['subject'];
$message = $_POST['message'];
$str = "Name: ".$name."\r\n\r\n"."Services: ".$services."\r\n\r\n"."Message: ".$message."\r\n\r\n".
$headers = "From: $email";
$sent = mail($to, $subject, $str, $headers) ;
I am working on a website with an Ajax contact form. Tried a lot, it successfully sends a mail without headers below is my code please help me to fix this
code
<div class="form">
<div class="title">
<h2 class="orange"><span class="orange">Contact</span> US</h2>
</div>
<div class="height15"></div>
<div id="return_message"></div>
<div class="field">
<label>First Name:</label>
<input name="name" type="text" />
</div>
<div class="field">
<label>Phone Number:</label>
<input name="phone" type="text" />
</div>
<div class="field">
<label>Email Address:</label>
<input name="email" type="text" />
</div>
<label>Message:</label>
<textarea name="message" cols="" rows=""></textarea>
<div class="clear"></div>
<a class="org_btn more submit" id="submit" href="#.">Submit</a> </div>
<script language="javascript">
$(document).ready(function() {
$("#menu_btn").click(function(){
$("#sub_menu").slideToggle("slow");
});
//Contact us form validation
$('#return_message').hide();
$('#submit').click(function(event){
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
var message = $('#message').val();
if( (name=='') || (phone=='') || (email=='') || (message=='') )
{
$('#name').addClass('error_active');
$('#phone').addClass('error_active');
$('#email').addClass('error_active');
$('#message').addClass('error_active');
}
else
{
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email))
{
alert("Please Enter valid email address");
$('#email').addClass('error_active');
}
else
{
$.ajax(
{
type: 'POST',
data: ({name : name, phone : phone, email : email, message : message}),
url: 'send_mail.php',
success: function(data)
{
if(data)
{
$('#return_message').show('slow').html("<p>Email has been sent...</p>");
$('#name').val('');
$('#phone').val('');
$('#email').val('');
$('#message').val('');
$('#name').removeClass('error_active');
$('#phone').removeClass('error_active');
$('#email').removeClass('error_active');
$('#message').removeClass('error_active');
}
else
{
$('#return_message').show('slow').html("<p>Email has not been sent...</p>");
}
}
});
}
}
});
});
</script>
php code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$to = "info#kodspider.com"; // Please put your email addres.
$subject = "Marthoman Vidyapeedom"; //Please put subject of your email.
if($phone!='')
{
$message2 = $message.'\r\nPhone:'.$phone;
}
else
{
$message2 = $message;
}
$message = $message.'\r\nPhone:'.$phone;
$headers = "From: ".$email;
$sent = mail( $to, $subject, $message2, $headers );
if($sent)
{
echo "success";
}
else
{
echo "error";
}
?>
you have given
<input name="name" type="text" />
but in jquery your calling
$('#name').val('')
in jquery # selector is used only for id
make change
<input name="name" id="name" type="text" />
for more details in jquery read this