js not passing form data for php mail - javascript

I'm a beginner attempting to create a HTML webpage. I'm using a free online template and trying to create a Contact Page. The contact calls a php script to send an email of the captured fields. I can get this to work when I send the email as pure php with no javascript or ajax. However when I try to use the javascript with the ajax code, the contents of the web form are not being passed. Two near identical issues have been raised here but I am finding the javascript to complicated for myself to understand as a beginner. The slight differences in the js has resulted in hours of trying to resolve without success.
js deleting submitted form data
PHP form post data not being received due to jQuery
The HTML code is
<div class="col-md-4 col-sm-12">
<div class="contact-form bottom">
<h2>Send a message</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Id">
</div>
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Your text here"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
The PHP script is called sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
The javascript is as follows
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $.post(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 contacting us. We will reply as soon as possible.</p>').delay(3000).fadeOut();
});
});
There are two issues, the first being that the form data doesnt pass when using the javascript code. The second is that it displays the message twice and sends two emails. I think the second issue is related to the php script calling the function again.
Help & guidance will be really appreciated, I am a beginner only attempting a small challenge.

The mail form appears to be deliberately disabled. It took me a while to fix it.
The code below will make it work. I hope this helps.
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
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 contacting us. We will reply as soon as possible.</p>').delay(3000).fadeOut();
});
});

Related

Contact form that doesn't refresh page on submit while using Wordpress

I have setup the following code to make a contact form that doesn't refresh the page when submitted.
HTML:
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="form-action">
</form>
JavaScript/AJAX request:
$("#contact-form").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = "<?php echo get_template_directory_uri(); ?>/library/contact-form.php";
var posting = $.post( url, {
name: $('#name').val(),
email: $('#email').val(),
subject: $('#subject').val(),
message: $('#message').val(),
});
posting.done(function( data ) {
alert('success');
});
});
PHP:
// Set $to as the email you want to send the test to.
$to = "my#email.com";
// Email subject and body text.
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$headers .= "Reply-To: ". strip_tags($_POST['email']) . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = $_POST["message"];
// send test message using wp_mail function.
if(isset(($_POST['name']), ($_POST['email']), ($_POST['message']), ($_POST["subject"]))) {
$sent_message = wp_mail( $to, $subject, $message, $headers );
} else {
};
//display message based on the result.
if ( $sent_message ) {
// The message was sent.
echo 'The test message was sent. Check your email inbox.';
} else {
// The message was not sent.
echo 'The message was not sent!';
}
The code works when I run it on my local website, It returns the success alert.
The PHP code also succeeds in sending the contact form information to my email address.
I get a 'the server responded with a status of 500 (internal error)' when I run it on my web server.
I think I must have overlooked something stupid here but I can't see it and hoping someone else can see it and help me out?
Thanks in advance!
This is how i do my ajax submission for a form. It's contains WordPress security measures, you can learn them from google in detail but small description will be provided by me.
HTML
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="contact_form" id="cf_action" url="<?= admin_url('admin-ajax.php'); ?>">
<?php wp_nonce_field( 'contact_form', 'contact_form_wpnonce' ); ?>
</form>
Javascript
jQuery(function($){
$("#contact-form").submit(function(e){
var url = $('#cf_action').attr('url');
$.ajax({
type: "POST",
url: url,
data: $("#contact-form").serialize(),
success: function(data) {
alert(data.data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
Function
add_action('wp_ajax_contact_form', 'contact_form_function');
add_action('wp_ajax_nopriv_contact_form', 'contact_form_function');
function contact_form_function()
{
if ( !isset($_POST['xyz_contact_email_meta_box_nonce']) && !wp_verify_nonce($_POST['xyz_contact_email_meta_box_nonce'], 'xyz_save_contact_email_data')) {
# code...
return;
}
$user_name = sanitize_text_field( $_POST['name'] );
$user_email = sanitize_email( $_POST['email'] );
$user_subject = sanitize_text_field( $_POST['subject'] );
$user_message = sanitize_textarea_field( $_POST['message'] );
$to = 'xyz#gmail.com';
$subject = $user_subject;
$body = 'Hi you recived a message from '.$user_name.'('.$user_email.'),<p>'.$user_message.'</p>';
$headers = array('Content-Type: text/html; charset=UTF-8');
$status = wp_mail( $to, $subject, $body, $headers );
if($status){
wp_send_json_success('sent successful');
}else{
wp_send_json_error('something went wrong');
}
}
Description
okay let me guide through WordPress a bit.
WordPress have already inbuilt functionality to handle ajax-request from it's theme's functions.php, you have to copy and paste html code where you want form to show, js code in footer and function code in functions.php
Here are some tips:-
wp_nonce_field = it's used for security purpose and prevent hackers to use form for different purpose.
Sanitize data to make sure you are not receiving any malicious code from your posted data, you can use esc_attr(it will convert any tags and script into html) too.
It's a good habit to send data back with WordPress default function wp_send_json_success & wp_send_json_error.
(Forgive me if you feel hard to understand since it's my first answer on stackoverflow)
Cheers!!

message alert not working

this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
Htmlcode and after html is js code
this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
--
ajax code
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">' + data.message + '</p>').delay(3000).fadeOut();
});
});
php code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
This is what your ajax call should look like
$('#main-contact-form').on('submit', function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url : $(this).attr('action'),
data : $(this).serialize(),
dataType : 'json',
type : 'POST',
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">' + data.message + '</p>').delay(3000).fadeOut();
});
});
make sure your ajax response which is
function(data)
is really an object variable
because if not this code will not execute because of error of data.message
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
also kindly check your network status check the response of that ajax request
using the dev tools F12
UPDATED ANSWER BELOW
so your response is json but still need to be parse in your javascript.
SOLUTION: Parse your ajax response to make it json object
data = JSON.parse(data);
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
The problem is, that you don't send your form data with the ajax-call.
Like adeneo wrote, you only have to add one line to your code.
data : $(this).serialize(),
Setting the data-type is relevant, because the destination needs to know in which format the data is sent.
Try using the Jquery-POST-function. It looks much better in the code.

How to redirect on button click using php

I am using a button on my form. I am trying to redirect to another page on button click after successful submission of user info. Every thing works properly except redirection. Here is the code I tried.
Html code:
<form role="form" id="contact-form" method="get">
<div class="form-group row">
<input type="email" id="email" name="email" placeholder="Enter your email" required="required" class="form-control input-lg" />
<input type="text" id="address" name="address" placeholder="Enter your address" required="required" class="form-control input-lg" />
<button type="submit" class="btn btn-t-primary">Show Me Now!</button>
</div>
</form>
Javascript code:
function contact() {
$("#contact-us-form").submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
form = $(this);
data = $(this).serialize();
$.post("contact.php", data, function(response){
form.trigger('reset');
});
}
Php code:
<?php
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
if (isset($_POST['email'])) {
$email = $_POST['email'];
$address= $_POST['address'];
$subject = "Message from: ".$email;
$content = "Email: " . $email."\n"
. "Address: " . $address;
$headers ='Reply-To: ' . $email . "\r\n";
mail('example#gmail.com', $subject ,$content, $headers );
header("Location:https://www.example.com");
echo 1;
}else {
echo 0;
}
?>
You can't redirect an ajax request from PHP, instead use this:
$(function() {
$("#contact-form").submit(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
form = $(this);
data = $(this).serialize();
$.post("contact.php", data, function(response) {
form.trigger('reset');
//Redirection
window.location.href = "https://www.google.com";
});
});
});
Just remove this header("Location:https://www.example.com"); from your PHP.
I hope this will help you.
Maybe you have to write the entire url when you are setting the header:
header("Location: http://www.google.com");
This isn't actually necessary.
Inside of the HTML form tag, add where you want to post the data to inside of the action attribute.
<form role="form" id="contact-form" method="get" action="postpage.php"> <!-- notice the action attribute !-->
Try this!
echo '<meta http-equiv=REFRESH CONTENT=0;url=./yourDestination.php>';
As we can see in the code, the page would refresh to the url you declared.
"Content = 0" means that it'll refresh after 0 seconds
You could modify the number if you want!
I wonder why you have set form method="get", but used $_POST variable under php code. Here's another version using POST method, try if it helps.
<?php
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
if (isset($_POST['email'])) {
$email = $_POST['email'];
$address= $_POST['address'];
$subject = "Message from: ".$email;
$content = "Email: " . $email."\n"
. "Address: " . $address;
$headers ='Reply-To: ' . $email . "\r\n";
mail('example#gmail.com', $subject ,$content, $headers );
header("location: https://google.com");
exit;
}
?>
<form role="form" id="contact-form" method="post">
<div class="form-group row">
<input type="email" id="email" name="email" placeholder="Enter your email" required="required" class="form-control input-lg" />
<input type="text" id="address" name="address" placeholder="Enter your address" required="required" class="form-control input-lg" />
<button type="submit" class="btn btn-t-primary">Show Me Now!</button>
</div>
</form>
You need to set the absolute address, including the protocol (https://) in your header location if you want to redirect to a new site.
header("Location: https://www.google.com")
Without the protocol, the location is assumed to be relative and will be appended to the existing domain.
Additionally, you should not echo anything after the headers.
First you have to write PHP code that handles Ajax Request:
if (isset($_POST['ajax_request'])) {
// write code;
echo "http://www.example.com"; // redirect url
}
Javascript:
jQuery(document).ready(function($) {
$.post('/path/to/file.php', {"ajax_request": true}, function(data, textStatus, xhr) {
window.location.href = data; // http://www.example.com
});
});
Hope this helps.

I want to use a modal to send mail, via a php file and I want the pop closed once submit is closed

I have a simple form that loads nicely via bootstrap modal once the page loads. I want to process and send the once I click submit and the modal should close immediately without refreshing the page. Below are my codes. It is not working. Please I need help. With a php file it sends the mail but it takes me to the php file and gets stuck there. I believe it's a small thing but I can't wrap my head around it.
$(function() {
$(window).load(function() {
$('#Modal').modal('show');
});
$('#btn_send').click(function(){
var name = $(":input[name='name']").val();
var email = $(":input[name='email']").val();
var varData = 'name=' + name + '&email=' +email;
$.ajax({
type: 'POST',
url: 'index.php',
data: varData,
success: function(){
alert('Mail sent. Thank you.');
}
});
});
});
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="form_pp">
<div id="Modal" class="modal fade in" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<div class="modal-header" style="margin-top:120px;">
<div class="modal-body">
<div class="form-group">
<input class="form-control" placeholder="YOUR FULL NAME" name="name" type="text" required autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="YOUR EMAIL ADDRESS" name="email" type="email" required>
</div>
<br>
<button type="submit" class="btn btn-default" style="color:#c13b01" id="btn_send">SEND</button>
<button type="button" class="btn btn-default" style="color:#c13b01" name="send" id="btn_cancel" data-dismiss="modal">CANCEL</button>
</div>
</div>
</div>
</div>
</div>
php file
if (isset($_POST['name']) && isset($_POST('email))) {
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = "Results from Online contact form:\n\n";
$email_from = $email;
$email_to = 'mail#mail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email. "\n\n" . 'Subject: ' . $subject;
#mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
}
Leandro's answer is part of your success. I would say that the reason the php script isn't working, is because it doens't get any data submited and therefor can't send an email
In order to retrieve the data from both the name as well as the email you need to change the part where it says
var name = $("name").val();
var email = $("recipientmail#mail.com").val();
to
var name = $(":input[name='name']").val();
var email = $(":input[name='email']").val();
That should help you to get your data over to the server.
with the help of #Eric Dohmen, I figured I missed out quotes and the correct block parenthesis for the email variable. Here it is:
if (isset($_POST['name']) && isset($_POST['email'])) {
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = "Results from Online contact form:\n\n";
$email_from = $email;
$email_to = 'mail#mail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email. "\n\n" . 'Subject: ' . $subject;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
}
else{
echo alert('Message did not send');
}

AJAX script alerts for contact form with PHP, Google reCAPTCHA, and SweetAlert

I am using an AJAX script to submit a basic contact form at the bottom of my HTML that uses Google reCAPTCHA. The html code is:
<div class="col-md-6">
<form role="form" id="form" action="form.php" method="post">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
<span class="help-block" style="display: none;">Please enter your name.</span>
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
<label for="exampleInputText1">Message</label>
<textarea class="form-control" rows="3" id="message" name="message" placeholder="Enter message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="I HAVE REMOVED MY SITE KEY"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
</div>
<button type="submit" id="Submit" data-loading-text="Sending..." class="btn btn-default">Submit</button>
</form>
</div>
<!-- Placed at the end of the document so the pages load faster -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="slick/slick.min.js"></script>
<script src="assets/js/smoothscroll.js"></script>
<script src="assets/js/jquery.stellar.min.js"></script>
<script src="assets/js/fancybox/jquery.fancybox.js"></script>
<script src="assets/js/main.js"></script>
<script src="alert/sweetalert2.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
I have created a very basic php to email me the data entered into the form.
<?php
//include CSS Style Sheet
echo "<link rel='stylesheet' type='text/css' href='alert/sweetalert2.css' />";
//include a javascript file
echo "<script type='text/javascript' src='alert/sweetalert2.min.js'></script>";
// Define some constants
define( "RECIPIENT_NAME", "Paul O'Shea" );
define( "RECIPIENT_EMAIL", "I HAVE REMOVED MY EMAIL" );
define( "EMAIL_SUBJECT", "Website Enquiry" );
$full_name;$email;$subject;$message;$captcha;
if(isset($_POST['name'])){
$name=$_POST['name'];
}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 '<script type="text/javascript">';
echo 'setTimeout(function () { swal("ERROR!","In order to avoid SPAM mail, you must confirm you are human. Please select IM NOT A ROBOT and complete the simple challenge","error");';
echo '}, 1000); </script>';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?I HAVE REMOVED MY SECRET KEYresponse=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo "<script type=\"text/javascript\">alert('Message Failed. Please try again'); location.href='index.html#contact';</script>";
}else
{
// If all values exist, send the email
if ( $name && $email && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
echo "<script type=\"text/javascript\">alert('Thanks for your enquiry! Your message has been sent to Paul and he will be in touch within 48hrs'); location.href='index.html#contact';</script>";
}
?>
The PHP has 3 alerts within it:
reCAPTCHA has not been run.
If reCAPTCHA fails.
Success message.
These PHP alerts work if i bypass the AJAX script, (however open a blank form.php) but don't work at all when I use the AJAX script. Therefore I get a success alert from the AJAX script - even if the reCAPTCHA has not been completed - and the form data has not been emailed.
This is my AJAX script:
<script type="text/javascript">
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
swal(
'Thanks for your enquiry!',
'Your message has been sent. Paul will be in contact soon.',
'success'
);
}
});
ev.preventDefault();
});
</script>
This gives the desired result, the email is sent, and the nice alert is shown over the original page, and when closed returns to original page. However, none of the alerts referenced in form.PHP are displayed. If user forgets to run reCaptcha - the same success alert is shown - even though there message will not be emailed.
Can anyone help me add the PHP alerts to the AJAX javascript? I tried copy and paste the same code - but am a little unsure of the appropriate way to format the code. Any help greatly appreciated! Thanks!
I would remove the <script> responses from your php script and instead use plain text, then I'd go with an AJAX approach of form submission.
There are plenty of examples using this (recommended in my opinion) approach, check the following two:
Using just jQuery: jQuery Ajax POST example with PHP
jQuery AJAX submit form
Another approach is to create one file with both your HTML and php in it,
and don't redirect your form post to another page but to itself.
However, this would invoke a page refresh.
Check the following example:
Refresh page after form submitting - Check 1st Answer
Keywords for further searching: post form, ajax, php, jquery, jquery form plugin malsup
EDIT 1 - Code
HTML/JS:
<div class="col-md-6">
<form role="form" id="form" action="form.php" method="post">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
<span class="help-block" style="display: none;">Please enter your name.</span>
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
<label for="exampleInputText1">Message</label>
<textarea class="form-control" rows="3" id="message" name="message" placeholder="Enter message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="I HAVE REMOVED MY SITE KEY"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
</div>
<button type="submit" id="Submit" data-loading-text="Sending..." class="btn btn-default">Submit</button>
</form>
</div>
<!-- Placed at the end of the document so the pages load faster -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="slick/slick.min.js"></script>
<script src="assets/js/smoothscroll.js"></script>
<script src="assets/js/jquery.stellar.min.js"></script>
<script src="assets/js/fancybox/jquery.fancybox.js"></script>
<script src="assets/js/main.js"></script>
<script src="alert/sweetalert2.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
$(document).ready(function(e) {
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if (data == "error")
{
swal("ERROR!","In order to avoid SPAM mail, you must confirm you are human. Please select IM NOT A ROBOT and complete the simple challenge","error");
}
else if (data == "fail")
{
swal("Failed", "Message Failed. Please try again!", "error");
location.href='index.html#contact';
}
else if (data == "success")
{
swal("Thanks for your enquiry!", "Your message has been sent to Paul and he will be in touch within 48hrs", "success");
location.href='index.html#contact';
}
else
{
swal("Something went wrong!", data, "error");
}
}
});
ev.preventDefault();
});
});
</script>
Your php script:
<?php
// Define some constants
define( "RECIPIENT_NAME", "Paul O'Shea" );
define( "RECIPIENT_EMAIL", "I HAVE REMOVED MY EMAIL" );
define( "EMAIL_SUBJECT", "Website Enquiry" );
$full_name;$email;$subject;$message;$captcha;
if(isset($_POST['name']))
{
$name=$_POST['name'];
if($name != filter_var($name, FILTER_SANITIZE_STRING))
{
echo "Name is not valid!";
exit(); // or exit w/e you please
}
}
else
{
echo "Name field is required!";
exit(); // or exit w/e you please
}
if(isset($_POST['email']))
{
$email=$_POST['email'];
if(! filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "Email is not valid!";
exit(); // or exit w/e you please
}
}
else
{
echo "Email field is required!";
exit(); // or exit w/e you please
}
if(isset($_POST['message']))
{
$message=$_POST['message'];
if($message != filter_var($message, FILTER_SANITIZE_STRING))
{
echo "Name is not valid!";
exit(); // or exit w/e you please
}
}
else
{
echo "Message field is required!";
exit(); // or exit w/e you please
}
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo 'error';
exit();
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?I HAVE REMOVED MY SECRET KEYresponse=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo 'fail';
// No need to exit() here, code ends after this anyway
}
else
{
// If all values exist, send the email
if ( $name && $email && $message )
{
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
echo "success";
}
else
{
echo "Name, email and message are required!";
}
// No need to exit() here, code ends after this anyway
}
?>
EDIT 2 - Validation (Added in code as well)
You can use php's filter_var function with the available filters
to validate your input. Likewise, if a validation fails you can echo and exit accordingly with a message like echo 'other' which would invoke the last if case at the JS above (just fix the title perhaps to something like "Input error" or "Invalid input").

Categories

Resources