Posting a form with google recaptcha via ajax - javascript

I have the following 'contact me' form (in a partial) in OctoberCMS
<form name="sentMessage" id="contactForm" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Phone Number</label>
<input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="g-recaptcha" id="gcaptcha" data-sitekey="sitekeydataCjaelksjEJlakch"></div>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</form>
When the user clicks submit - it's handled via javascript (which is what helps with input validation). I'm using JQuery.
The JS looks like this:
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var gcaptcha = $("#gcaptcha").data('sitekey');
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message,
gcaptcha: gcaptcha
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
The contact_me.php form looks like this:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$secret = "alkfejasupersecretkeyalkjeociyseh13987fa9s8df7";
$gcaptcha = $_POST['gcaptcha'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$gcaptcha."&remoteip=".$remoteip;
$result = json_decode($url, true);
var_dump($result);
/*
if ($result['success'] == 1) {
//do mail here
}
// Create the email and send the message
$to = 'myemail#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
*/
?>
As you can see - I'm trying to just see if I'm even getting to the contact_me.php form which it doesn't appear I am. Before I had commented it out - the mail never sent - which is why I started playing around trying to see if my data is even hitting the contact_me.php page. I see the success message when submitting - but the data never goes anywhere and no email is ever had.
I can see in Firebug that the data is posting to contact_me - but I can't tell much beyond that. The var_dump doesn't work and I'm in need of further assistance to either better troubleshoot this issue or figure out what isn't working.

After a lot of help from Xorifelse in the comments I realized that the code was probably fine (or at least suitable).
I ended up going a different direction. I updated the form a bit so it looks like this:
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>Contact Me</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<form name="sentMessage" id="contactForm" data-request="onSend" data-request-success="alert('We have received your email. Thank you!'); this.reset();" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input name="name" type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input name="email" type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Phone Number</label>
<input name="phone" type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea name="contact-msg" rows="5" class="form-control" placeholder="Message" id="contact-msg" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="g-recaptcha" id="sitekey" data-sitekey="gcaptchasitekey3897vadf834fadf"></div>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
Note the 'onSend' data-request parameter.
In the default layout - I put this snippet of PHP to handle the actual processing (the onSend function):
function onSend()
{
if(empty(post('name')) ||
empty(post('email')) ||
empty(post('phone')) ||
empty(post('contact-msg')) ||
empty(post('g-recaptcha-response')) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "Please fill out all required fields.";
return false;
}
// Collect input
$name = post('name');
$email = post('email');
$phone = post('phone');
$body = post('contact-msg');
$response = post('g-recaptcha-response');
$remoteip = $_SERVER['REMOTE_ADDR'];
$secret = "32supersecretkeyackjaBcjeLCJelahd832CDo";
$url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$remoteip);
$response = json_decode($url, true);
// Form Validation
$validator = Validator::make(
[
'name' => $name,
'email' => $email,
'phone' => $phone,
'contact-msg' => $body,
],
[
'name' => 'required',
'email' => 'required|email',
'contact-msg' => 'required',
]
);
if ($validator->fails())
{
$messages = $validator->messages();
throw new ApplicationException($messages->first());
}
// Make sure the captcha is verified before sending
if (isset($response['success'])&&$response['success']=="true"){
$to = config('mail.from.address');
$params = compact('name','email','phone','body');
Mail::sendTo($to, 'freelance::mail.contact', $params);
return true;
}
else {
return false;
}
}
I was able to trim down the JS file to this:
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
So it provides active validation as the user is typing (which is great).
This method also required a little additional setup on the backend:
You need to create a new 'Mail Template' (code: freelance::mail.contact) in the Settings portion of the backend (and of course, make sure your mail settings are setup)
I would have liked to do a little more JS once the submission is successful - so maybe in the future I'll work that into it - but this is now working as intended.

Related

How to submit a contact form with Google recaptcha v2 and PHP with a Boostrap success alert

I have a contact form on a website, and I am trying to submit the form using Google recaptcha v2, (select the boxes which have a certain image in them). At the moment, the form successfully sends and is received exactly as I want it to; however, I want to create a 'success' alert using Bootstrap, but for some reason this is not working.
If you take a look at the last part of my PHP file I have the following code snippet:
if($responseKeys["success"]) {
mail($to,$email_subject,$email_body,$headers);
} else {
echo '<h2>This has been unsuccessful according to our security checks</h2>';
}
And the 'mail' command seems to work. But anything else I try to put in there, for example
echo '<h2>success!</h2>'
for example, it doesn't get rendered. Ideally, upon a success submit I would like the following to take place:
The form to refresh to blank
A success alert using Bootstrap show at the top of the page
But I am having trouble implementing these.
Here is the entire PHP file:
<?php
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$email = $_POST['email'];
$number = $_POST['number'];
$company = $_POST['company'];
$message = $_POST['message'];
$email_from = "Your website";
$email_subject = "You have a new submission form from Your Website";
$email_body = "First Name: $Fname.\n".
"Last Name: $Lname.\n".
"Email Address: $email.\n".
"Telephone Number: $number.\n".
"Company Name: $company.\n".
"Message: $message.\n";
$to = "hello#yourwebsite.co.uk";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
$captcha;
if(isset($_POST['email'])){
$email=$_POST['email'];
}
if(isset($_POST['message'])){
$message=$_POST['message'];
}
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the "I am not a robot" checkbox"</h2>';
exit;
}
$secretKey = 'somesecretlettersandnumbers';
$ip = $_SERVER['REMOTE_ADDR'];
// post request to the server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
// should return JSON with success as true
if($responseKeys["success"]) {
mail($to,$email_subject,$email_body,$headers);
} else {
echo '<h2>This has been unsuccessful according to our security checks</h2>';
}
?>
And here is the HTML form:
<form action="contact.php" id="contact-form" method="POST" role="form">
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_name">First Name*</label>
<input id="form_name" type="text" class="form-control" name="Fname" placeholder="David" required data-error='Please fill in your first name'>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="form_lastname">Last name*</label>
<input id="form_lastname" type="text" class="form-control" name="Lname" placeholder="Beckham" required data-error="Please fill in your last name">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_email">Email address*</label>
<input id="form_email" type="email" class="form-control" name="email" placeholder="becks#example.com" required data-error="Please provide your email address">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="form_number">Contact number*</label>
<input id="form_number" type="number" class="form-control" name="number" placeholder="01234567890" required data-error="Please provide a contact number">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_company">Your company name</label>
<input id="form_company" type="text" class="form-control" name="company" placeholder="Ex-footballers r us">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_message">Your message*</label>
<textarea id="form_message" class="form-control" name="message" cols="30" rows="10" placeholder="Here's my message" required></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="g-recaptcha" data-sitekey="datasitekeynumbersandletters"></div>
</div>
</div>
<div class="row">
<div class="col">
<input type="submit" class="btn btn-outline-brand btn-block" name="submit" value="Send enquiry">
</div>
</div>
</form>
I have tried following this tutorial:
Bootstrap success alert upon form submition via javascript
Edited to add the only JS I have for this file:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
without success.
Thank you in advance

My contact form does not work, submit button is not functioning

I am using a Bootstrap theme for my portfolio website. As far as I know, I changed all the parameters in the default php- and js-files in order for my contact form to work. I also made sure I have the correct settings in my server. However, when I press the submit button, it does not send anything. I'm also not receiving any sort of error message.
Any idea where I went wrong/how to fix this issue?
In Javascript:
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
},
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true);
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>')
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false);
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
The PHP-file associated with it(I marked out my email):
<?php
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$to = '*****#******.com';
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#********.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
And the HTML-snippet:
<!-- Contact -->
<section id="contact">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading text-uppercase">Feel free to contact me!</h2>
<h3 class="section-subheading text-muted">How can I help you?</h3>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<form id="contactForm" name="sentMessage" novalidate="novalidate">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" id="name" type="text" placeholder="Your Name *" required="required" data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input class="form-control" id="email" type="email" placeholder="Your Email *" required="required" data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input class="form-control" id="phone" type="tel" placeholder="Your Phone *" required="required" data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" id="message" placeholder="Your Message *" required="required" data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-center">
<div id="success"></div>
<button id="sendMessageButton" class="btn btn-primary btn-xl text-uppercase" type="submit">Send Message</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>

Address box fails to be shown in the email

I was wondering if anyone could help me with my issue, When ever the form is submitted the street form does not show up in the email I receive. I don't understand why it might not be working I've looked through the php and JS but cant understand why it won't work. Here i the JS:
(function($){
$(document).ready(function() {
/* ---------------------------------------------- /*
* Contact form ajax
/* ---------------------------------------------- */
$('#contact-form').find('input,textarea').jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault();
var submit = $('#contact-form submit');
var ajaxResponse = $('#contact-response');
var name = $('#contact-form [name="name"]').val();
var lastname = $('#contact-form [name="lastname"]').val();
var address = $('#contact-form [name="address"]').val();
var email = $('#contact-form [name="email"]').val();
var message = $('#contact-form [name="message"]').val();
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
dataType: 'json',
data: {
name: name,
lastname: lastname,
address: address,
email: email,
message: message,
},
cache: false,
beforeSend: function(result) {
submit.empty();
submit.append('<i class="fa fa-cog fa-spin"></i> Wait...');
},
success: function(result) {
if(result.sendstatus == 1) {
ajaxResponse.html(result.message);
$form.fadeOut(500);
} else {
ajaxResponse.html(result.message);
}
}
});
}
});
}); })(jQuery);
Here is the HTML:
<div class="row">
<div name="contactform" class="col-sm-8 col-sm-offset-2">
<form id="contact-form" method="post" novalidate>
<div class="row">
<div class="col-md-6 form-group">
<label class="sr-only">First Name</label>
<input type="text" class="form-control input-lg" name="name" placeholder="First Name" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-6 form-group">
<label class="sr-only">Last Name</label>
<input type="text" class="form-control input-lg" name="lastname" placeholder="Last Name" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-6 form-group">
<label class="sr-only">Address</label>
<input type="text" class="form-control input-lg" name="address" placeholder="Address" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 form-group">
<label class="sr-only">E-mail Address</label>
<input type="email" class="form-control input-lg" name="email" placeholder="E-mail Address" value="" required="">
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 form-group">
<textarea class="form-control input-lg" rows="7" name="message" placeholder="Message - Please include Address and Telephone number" required=""></textarea>
<p class="help-block text-danger"></p>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-lg btn-round btn-dark" >Send Email</button>
</div>
</div><!-- .row -->
</form>
<!-- Ajax response -->
<div id="contact-response" class="ajax-response text-center"></div>
</div>
</div>
And here is the php:
<?php
// Mail settings
$to = "****#*******.co.uk";
$subject = "PB Enquiry Form - " . $_REQUEST['lastname'];
// You can put here your email
$header = "From:****#*******.co.uk\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/plain; charset=utf-8\r\n";
$header.= "X-Priority: 1\r\n";
if (isset($_POST["name"]) && isset($_POST["lastname"]) && isset($_POST["email"]) && isset($_POST["message"])) {
$content = "First Name: " . $_POST["name"] . "\r\n";
$content .= "Last Name: " . $_POST["lastname"] . "\r\n";
$content .= "Address: " . $_POST["address"] . "\r\n";
$content .= "Email: " . $_POST["email"] . "\r\n";
$content .= "Message: " . $_POST["message"] . "\r\n";
if (mail($to, $subject, $content, $header)) {
$result = array(
"message" => "Thank you for contacting us.",
"sendstatus" => 1
);
echo json_encode($result);
} else {
$result = array(
"message" => "Sorry, something is wrong.",
"sendstatus" => 0
);
echo json_encode($result);
}
}
I cannot figure out why it won't work and would be delighted if someone could help me.
If you do have a solution then please give an example of how to input the solution as I am new to the languages, Thank you!

FormData() coudn't extract form parameters from HTML

I have written a jQuery function whose purpose is to extract parameters from a form upon submitting it. To extract form data, I am using the function FormData() function. After that, I have also written a loop to print the form entries, but nothing is getting printed in the console.
My HTML form:
<div class="form-contact">
<form name="sentMessage" id="contactForm" class="contact-form" method="post" novalidate>
<div class="row">
<div class="col-md-6">
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Name<span>*</span></label>
<input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Email Address<span>*</span></label>
<input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block"></p>
</div>
</div>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Subject</label>
<input type="tel" class="form-control" placeholder="Subject" id="subject">
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Message<span>*</span></label>
<textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block"></p>
</div>
</div>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12 text-right">
<button type="submit" name="button" class="btn btn-primary btn-lg">Send Message</button>
</div>
</div>
</form>
</div>enter code here
My JS file:
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
/*var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();*/
var firstName = name; // For Success/Failure Message*/
// Check for white space in name for Success/Fail message
var dat=new FormData($('#contactForm')[0]);
if(firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
for (var pair of dat.entries())
{
console.log(pair[0]+ ', '+ pair[1]);
}
$.ajax({
type: "POST",
url: "/signup",
data: dat,
processData: false,
contentType: false,
/*{
name: name,
subject: subject,
email: email,
message: message
},*/
//cache: false,
success: function(result) {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function(error) {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
console.log(error);
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
// $("a[data-toggle=\"tab\"]").click(function(e) {
// e.preventDefault();
// $(this).tab("show");
// });
});
Use this to get all the form parameters on client side
Var dat = $(this).serializeArray();
//this contains object of form submitted
For(Var i=0;i
//serializeArray returns an array of parameters which are not disabled and have name attribute

Why do I receive an empty email? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Why are the field values not included in my email? I receive an empty email.
HTML
<div class="contact-form wow fadeIn" data-wow-duration="1000ms" data-wow-delay="600ms">
<div class="row">
<div class="col-sm-6">
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="row wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="300ms">
<div class="col-sm-6">
<div class="form-group">
<input type="text" id="name" name="name" class="form-control" placeholder="Name" required="required">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="email" id="email" name="email" class="form-control" placeholder="Email Address" required="required">
</div>
</div>
</div>
<div class="form-group">
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject" required="required">
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control" rows="4" placeholder="Enter your message" required="required"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn-submit">Send Now</button>
</div>
</form>
</div>
JavaScript
var form = $('#main-contact-form');
form.submit(function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function() {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function(data) {
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact you</p>').delay(6000).fadeOut();
});
});
PHP
<?php
$name = #trim(stripslashes($_POST['name']));
$headers = 'From:'. #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$temp_name = 'Client name='.$name."\n\n\n";
$temp_text = 'client query='.#trim(stripslashes($_POST['message']));
$message = $temp_name.$temp_text;
$to = 'svasu1850#gmail.com';
if(#mail($to, $subject, $message, $headers))
{
$result="Thanks for contacting us";
}else{
$result="retry after some time";
}
?>
You are using your javascript to prevent the default form submission. This stops the posting of the input from your user, unless you capture it and choose to send it along inside your ajax code.
$.ajax({
...
data: $("#main-contact-form").serialize(),
...
})
See more here: jQuery - Getting form values for ajax POST

Categories