Bootstrap Contact Form with PHP, jQuery and AJAX - javascript

Hi having a problem with my contact form submission ,Its a Bootstrap template, its got JQuery validation, but there wasn't any PHP file for contact, i tried many different code for contact.php but it doesn't work,
some of them showing "message sent successfully" but i didn't receive any email. i am using "Google Apps For Work" as my email client only. please help, really appreciate.
(Sorry about my poor English.)
Here the code for index.php`
<form action="Contact.php" method="post" id="sky-form3" class="sky-form contact-style">
<fieldset>
<label>Name</label>
<div class="row">
<div class="col-md-7 margin-bottom-20 col-md-offset-0">
<div>
<input type="text" name="name" id="name" class="form-control">
</div>
</div>
</div>
<label>Email <span class="color-red">*</span></label>
<div class="row">
<div class="col-md-7 margin-bottom-20 col-md-offset-0">
<div>
<input type="text" name="email" id="email" class="form-control">
</div>
</div>
</div>
<label>Message</label>
<div class="row">
<div class="col-md-11 margin-bottom-20 col-md-offset-0">
<div>
<textarea rows="8" name="message" id="message" class="form-control"></textarea>
</div>
</div>
</div>
<p><button type="submit" class="btn-u btn-brd btn-brd-hover btn-u-dark">Send Message</button>
<button type="reset" class="btn-u btn-brd btn-brd-hover btn-u-dark">Reset Messages</button></p>
</fieldset>
<div class="message">
<i class="rounded-x fa fa-check"></i>
<p>Your message was successfully sent!</p>
</div>
</form>
Here the code for my contact.php file
<?php
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
<?php
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'contact#vertigosourcing.com';
$name = addslashes(trim($_POST['name']));
$Email = addslashes(trim($_POST['email']));
$message = addslashes(trim($_POST['message']));
$array = array('nameMessage' => '', 'emailMessage' => '', 'messageMessage' => '');
if(!isEmail($Email)) {
$array['emailMessage'] = 'Invalid email!';
}
if($subject == '') {
$array['nameMessage'] = 'Empty name!';
}
if($message == '') {
$array['messageMessage'] = 'Empty message!';
}
if(isEmail($Email) && $name != '' && $message != '') {
// Send email
$headers = "From: " . $Email . " <" . $Email . ">" . "\r\n" . "Reply-To: " . $Email;
mail($emailTo, $subject . " (contact request from)", $message, $headers);
}
}
?>

If you are using xampp/lamp/wamp, it won't work that easy, you have to activate some functions to send an email from a localhost, I think that's the problem because you have no mistakes in your code.
You can also try using #mail() instead of mail().

Related

Wordpress PHP Contact form - problem with displaying message about sent mail

I'm trying to develop a contact form for a language school website that runs on Wordpress.
Disclaimer: I'm about 6 months into coding, so please forgive me for being new to this. I'm developing my own theme and I wanted to limit usage of plugins to bare minimum for safety reasons - I prefer to learn how to write stuff myself instead on relying on updates of a third-party plus the courses I follow on Wordpress dev listed it as a good practice to avoid unnecessary plugins.
Update: I tried implementing plugins, but they either broke my page or didn't work anyway.
The problem is listed below in bold.
What I want to achieve:
Simple contact form that takes following info: name, email, course, phone (optional) and a message.
Validate the form if user provided correct info - I can't make the
user provide valid info, but at least I want to lock number into
numbers only range and check if email is correct.
Check if user is human (Captcha).
Send the email to my address and provide a copy to the sender.
Inform the user whether the action was a success or a failure.
What I succeeded with:
Mail gets sent.
Captacha seems to be working and filtering out attempts that do not click on it.
What 'kinda works':
The PHP doesn't seem to validate the form. I used HTML type and require instead, but I've read that solution is not ideal. I tried to use JS to write some functions that would prevent unwanted input, but I couldn't get it to work properly. I decided to ask the question first in case it might be a dead end. JS seems to be working on my Wordpress as I'm using Bootstrap and some custom JS for certain features so I'm pretty sure the code gets executed, but I wanted to ask first if that's the correct way of approach it before I invest my time in it.
What I have a problem with:
It is imperative to me that the user gets feedback from the page whether the email has been sent or not for obvious business-client communication reasons. I tried two solutions found on SO:
Injecting JS alert into PHP's echo inside conditional (JS doesn't get executed)
Using header method to redirect into thank-you.page that informs about success or error.page that
informs about a failure and recommends another avenue of contact
What went wrong: the second solution got executed properly, the user gets redirected to site.com/thank-you or site.com/error, however the browser crashes due to 'too many redirects'.
I tried googling, I tried different solutions from tutorials. What would be your recommendation?
My code:
<?php
$nameErr = $emailErr = $courseErr = $phoneErr = "";
$name = $email = $course = $comment = $phone = "";
$thank_you = wp_redirect( '"'.home_url().'/thank-you"', 301 );
$error = wp_redirect( '"'.home_url().'/error', 301 );
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Give name";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Need email";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Email incorrect";
}
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!is_numeric($number)) {
$phoneErr = "Bad number";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["course"])) {
$courseErr = "Pick course";
} else {
$course = test_input($_POST["course"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST['g-recaptcha-response']))
{
$secret = 'mySecretKey';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
$message = "g-recaptcha verified successfully";
if(isset($_POST['submit'])){
$to = "myEmail#mail.org"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$course = $_POST['course'];
$phone = $_POST['phone'];
$comment = "Form submission";
$comment2 = "Copy of your form submission";
$message = "Name:" . $name . "Interested in " . $course. " Number" . $phone . " " . " Wrote" . "\n\n" . $_POST['comment'];
$message2 = "Copy " . $name ."\n\n" . "Interested in:" . $course . "\n\n" . $_POST['comment'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$comment,$message,$headers);
mail($from,$comment2,$message2,$headers2);
// sends a copy of the message to the sender
header($thank_you);
// This redirects to page thanking for contact.
}
else
header($error);
// This redirects to page informing about failure.
$message = "couldn't verify Captcha. Email not sent.";
echo '<script type="text/javascript">mailNotSent();</script>';
}
?>
<section id="contact" class="contact">
<div class="container pseudonest">
<div class="pseudonest contact__head--nest">
<h1 class="display-5 lh-1 mb-2 contact__head--pseudocircle contact__head--header mx-auto">Enroll now</h1>
</div>
<div class="container m-auto">
<div class="d-flex justify-content-center contact__form">
<div class="col-md-7 col-lg-8">
<form action="" method="post">
<form class="needs-validation" novalidate>
<div class="row g-3">
<div class="col">
<label for="name" id="nameHeader" class="form-label">Name</label>
<input type="text" class="form-control radio__margin" id="name" name="name"
placeholder="" value="<?php echo $name;?>" required>
<div class="invalid-feedback">
<?php echo $nameErr;?>
</div>
<label for="email" class="form-label">Email</label></label>
<input type="email" class="form-control radio__margin" id="email" name="email"
placeholder="you#example.com" value="<?php echo $email;?>" required>
<div class="invalid-feedback">
<?php echo $emailErr;?>
</div>
<label for="phone" class="form-label">Phone</label></label>
<input type="number" class="form-control radio__margin" id="phone" name="phone"
pattern="[0-9]+" placeholder="+48 111 222 333" value="<?php echo $phone;?>">
<div class="invalid-feedback">
<?php echo $phoneErr;?>
</div>
</div>
<div class="col radio__col">
<label for="firstName" class="form-label">Course?</label>
<div class="row radio__section">
<label class="radio__container">English
<input type="radio" name="course"
<?php if (isset($course) && $course=="English") echo "checked";?>
value="English">
<span class="radio__checkmark"></span>
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Polish") echo "checked";?>
value="Polish">
<span class="radio__checkmark"></span>Polish
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Italian") echo "checked";?>
value="Italian">
<span class="radio__checkmark"></span>Italian
</label>
<span class="error"> <?php echo $courseErr;?></span>
</div>
</div>
</div>
<div class="col-12 mb-5">
<label for="email-content" class="form-label">Content</label>
<div class="input-group has-validation">
<textarea class="form-control" rows="5" name="comment"
cols="30"><?php echo $comment;?></textarea>
<div class="invalid-feedback">
</div>
</div>
</div>
<form id="frmContact" action="varify_captcha.php" method="POST" novalidate="novalidate">
<div class="g-recaptcha my-3" data-sitekey="mySiteKey">
</div>
<input type="submit" name="submit" value="Send" id="submit"
class="btn btn-primary contact__form--btn">
<div id="fakeSubmit" class="btn btn-primary contact__form--btn hidden">Fill the form
</div>
</form>
</form>
</div>
</div>
</section>

theme php contact form

I purchased several themes so that I could build two websites. the theme that I like the most comes with a non-functional contact form. I have tried to integrate the contact forms from the other themes into it but they will not work no matter what I do. I know that one of them works fine because I am using it on another site and it works with no issue. (for transparency the working form is being used in the theme that it came with.) is there a possibility that I am missing something?
I've copied and pasted the exact forms into the theme site and included the Js files that deal with the contact form and all I can get are errors when I try to test it live.
this is the code for the form:
<section id="contact" class="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<h3 class="title-normal">Contact Form</h3>
<form id="contact-form" action="contact-form.php" method="post" role="form">
<div class="error-container"></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Name</label>
<input class="form-control form-control-name" name="name" id="name" placeholder="" type="text" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Email</label>
<input class="form-control form-control-email" name="email" id="email" placeholder="" type="email" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Subject</label>
<input class="form-control form-control-subject" name="subject" id="subject" placeholder="" required>
</div>
</div>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control form-control-message" name="message" id="message" placeholder="" rows="10" required></textarea>
</div>
<div class="text-right"><br>
<button class="btn btn-primary solid blank" type="submit">Send Message</button>
</div>
</form>
</div>
</div>
</div>
</section>
this is a copy of the php:
<?php
//Add your information here
$recipient = "info#domain.us";
//Don't edit anything below this line
//import form information
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$name=stripslashes($name);
$email=stripslashes($email);
$subject=stripslashes($subject);
$message=stripslashes($message);
$message= "Name: $name, Subject: $subject \n\n Message: $message";
/*
Simple form validation
check to see if an email and message were entered
*/
//if no message entered and no email entered print an error
if (empty($message) && empty($email)){
print "No email address and no message was entered. <br>Please include an email and a message";
}
//if no message entered send print an error
elseif (empty($message)){
print "No message was entered.<br>Please include a message.<br>";
}
//if no email entered send print an error
elseif (empty($email)){
print "No email address was entered.<br>Please include your email. <br>";
}
//mail the form contents
if(mail("$recipient", "$subject", "$message", "From: $email" )) {
// Email has sent successfully, echo a success page.
echo '<div class="alert alert-success alert-dismissable fade in">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">×</button>
<p>Email Sent Successfully! We Will get back to you shortly</p></div>';
} else {
echo 'ERROR!';
}
here is the Js
$('#contact-form').submit(function(){
var $form = $(this),
$error = $form.find('.error-container'),
action = $form.attr('action');
$error.slideUp(750, function() {
$error.hide();
var $name = $form.find('.form-control-name'),
$email = $form.find('.form-control-email'),
$subject = $form.find('.form-control-subject'),
$message = $form.find('.form-control-message');
$.post(action, {
name: $name.val(),
email: $email.val(),
subject: $subject.val(),
message: $message.val()
},
function(data){
$error.html(data);
$error.slideDown('slow');
if (data.match('success') != null) {
$name.val('');
$email.val('');
$subject.val('');
$message.val('');
}
}
);
});
return false;
});

PHP mail not sending form data. Data is blank in email

Somehow the form is not sending the main data which is basically the name, email and number. I's appreciate any/all help!
Here is the PHP i used.
<?php
$browser = $_SERVER['HTTP_USER_AGENT'];
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
//get user's ip address
$geoplugin->locate();
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$mess .= "---------------|OFFERS USER EMAIL SUBSCRIPTION|---------------\n";
$mess .= "Full Name : " . $_POST['cn'] . "\n";
$mess .= "Email Address : " . $_POST['em'] . "\n";
$mess .= "Number: " . $_POST['pn'] . "\n";
$mess .= "IP Address : " .$ip. "\n";
$mess .= "--------------------------------------------\n";
$mess .= "City: {$geoplugin->city}\n";
$mess .= "Region: {$geoplugin->region}\n";
$mess .= "Country Name: {$geoplugin->countryName}\n";
$mess .= "Country Code: {$geoplugin->countryCode}\n";
$mess .= "---------------------------------------------\n";
$from = "XOXLERT";
$to = "mail#mail.com";
$hi = mail($to, "OFFERS EMAIL SUBSCRIPTION | ".$ip , $mess);
?>
And here goes the HTML Form Element.
<div class="row main-form">
<div class="">
<div class="col-md-4">
<h4 class="fc-white ff-primary">Sign up now <span class="">And Save BIG</span> For Later Use</h4>
<p class="ff-primary fs-xlarge fc-white">On your Custom Logo & Website</p>
</div>
<div class="col-md-8">
<div class="rightform" id="mainBanForm">
<form class="jform validate" action="https://placmedia.com/thank_you.php">
<div class="col-md-6">
<div class="bm-field-top inpt-rel">
<!--<label class="">Name</label>-->
<span class="user-icon-top"></span> <input type="text" placeholder="Name" name="cn" class="required">
</div>
</div>
<div class="col-md-6">
<div class="bm-field-top inpt-rel">
<!--<label class="">Email</label>-->
<span class="user-email-top"></span> <input type="text" name="em" class="required email" placeholder="Email">
</div>
</div>
<div class="col-md-6">
<div class="bm-field-top pnfields">
<!--<label class="">Phone Number</label>-->
<input type="text" name="pn" id="phone" class="number required" placeholder="Phone Number" />
</div>
</div>
<div class="col-md-6">
<div class="bm-field-top-nbg whbgnone">
<input type="submit" value="Reserve Now" class="get-button ff-primary">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
What i don't understand is why i am receiving just the IP (of course those are pre-populated by the geo-plugin script) and other form data omitted
Set the form method to POST. HTML forms default to GET method.
You need to specify the method type. You're trying to access via POST yet the default method is GET.
<form class="jform validate" action="https://placmedia.com/thank_you.php" method="POST">

Modal window closes on submit

I have a form in a bootstrap modal window and what is happening, is when I click the 'send' button, the modal closes and a white page displays the result of my action call to contact-form.php and shows the error message for blank field but thid should be showing in the message div in the form in the the modal window.
I am obviously doing something fundementally wrong and would appreciate any help you can offer. I wouls have done a snippet but couldn't see how to include php code.
Many thanks
Bootstrap V3.3.7
UPDATE: The form works fine if i use as normal form outside of the modal
window.
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal__title"><div style="color: white; margin-top: -14px; margin-left: 36px;">Contact Us</div></h2>
<div style="color: white; margin-left: 36px; margin-bottom: 20px;">If you need to contact us, please use this form and we shall respond as soon as possible. Thanks</div>
</div>
<div class="modal-body">
<div class="content-block contact-3">
<div class="container">
<div class="row">
<div class="col-md-9">
<div id="contact" class="form-container">
<div id="message"></div> <-ERROR SHOULD BE DISPLAYED HERE
<form method="post" action="js/contact-form.php" name="contactform" id="contactform">
<div class="form-group">
<input name="name" id="name" type="text" value="" placeholder="Name" class="form-control" />
</div>
<div class="form-group">
<input name="email" id="email" type="text" value="" placeholder="Email" class="form-control" />
</div>
<div class="form-group">
<input name="phone" id="phone" type="text" value="" placeholder="Phone" class="form-control" />
</div>
<div class="form-group">
<textarea name="comments" id="comments" class="form-control" rows="3" placeholder="Message" id="textArea"></textarea>
<div class="editContent">
<p class="small text-muted"><span class="guardsman">* All fields are required.</span> Once we receive your message we will respond as soon as possible.</p>
</div>
</div>
<div class="form-group">
<button class="btn btn-default" type="button" class="modal" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit" id="cf-submit" name="submit">Send</button>
</div>
</form>
</div>
<!-- /.form-container -->
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!--// END Contact 3-1 -->
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
contact-form.php
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits and no spaces.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "yourname#yourdomain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
sendmail.js
jQuery(document).ready(function () {
$('#contactform').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
$("#message").fadeOut(500, function () {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
},
function (data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if (data.match('success') != null) {
$('#contactform').fadeOut('slow');
$("#message").delay(3000).fadeOut();
$("#contactform").delay(4000).fadeIn();
$("#contactform").css("margin-top", "40px !important");
$("#contactform").trigger("reset");
}
}
);
});
return false;
});
});
I can't test you code but in my opinion i would not do the submit action with $(form).submit().... also if you are doing a event.preventDefault(), i explain better, you are doing an ajax call and with different errors you have differents answers, so in your place i would delete the action in the html at on click of the send button i would do an ajax call and manage the answer.Try in this way, because i think that if you use the submit in that way the browser interpret the submit form also because you are using the action url to send the call.
$('#cf-submit').click(function(){
name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
comments = $('#comments').val();
$.ajax({
url : 'js/contact-form.php',
type : 'POST',
data : {
name : name,
email : email,
phone : phone,
comments : comments,
},
dataType : 'html',
success : function(response){
$('#message').html(response);
}
});
});
I think you forget to put exit(); at the end of file contact-form.php

How do I force form submit with Jquery

Wish you all a happy 2015!
I have a simple contact us php form. I am validating it with parsley.js. The validation works fine but I am receiving a lot of spam mails.
I believe if I can force the form to be submitted only if Jquery is enabled, then it should solve my problem (right?).
I'm not an expert with PhP/ Jquery and any help will be appreciated.
Here is my PHP code
<?php
// Define Variables i.e. name tag, as per form and set to empty
$contact_name = $contact_email = $contact_phone = $contact_message = "";
// Sanitize data and use friendly names
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["contact_name"]);
$email = test_input($_POST["contact_email"]);
$phone = test_input($_POST["contact_phone"]);
$message = test_input($_POST["contact_message"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Set values
$to = 'info#foryourservice.in';
$subject = 'New Message from Website';
$headers = 'From: info#domainname.com' . "\r\n" .
'Reply-To: info#domainname.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Set Email content
$emailcontent = "A new message has been submitted from the website.
\n
Name : $name
Email : $email
Phone : $phone
Message : $message";
// Mail function
$send_contact=mail($to,$subject,$emailcontent,$headers);
if($send_contact){
header('Location: index.php#contactusform');
}
else {
echo "<script type='text/javascript'>alert('We encountered an ERROR! Please go back and try again.');</script>";
}
?>
Here is my HTML ( Im using Twitter Bootstrap)
<form role="form" method="POST" action="contactusform.php" id="contactusform" data-parsley-validate>
<div class="col-xs-6">
<div class="form-group" style="margin-bottom: -5px">
<label for="input1"></label>
<input type="text" name="contact_name" class="form-control" id="input1" placeholder="Name*" required data-parsley-required-message="Please enter your name">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input2"></label>
<input type="email" name="contact_email" class="form-control" id="input2" placeholder="Email Address*" data-parsley-trigger="change" required data-parsley-required-message="Please enter a valid Email address">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input3"></label>
<input type="tel" name="contact_phone" class="form-control" id="input3" placeholder="Phone Number*" required data-parsley-type="digits" data-parsley-minlength="10" data-parsley-maxlength="10" data-parsley-required-message="Please enter a 10 digit number">
</div>
<br>
<div class="form-group">
<button type="submit" id="contactbutton" class="btn btn-primary" style="background-color: #A8B645; border-color: transparent">Submit</button>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="input4"></label>
<textarea name="contact_message" class="form-control" rows="7" id="input4" placeholder="Message*" required required data-parsley-required-message="Say something!"></textarea>
</div>
</div>
</form>
This is what the Spam Email looks like :
A new message has been submitted from the website.
Name : お買い得アナスイ ミロード大壳り出しランキング
Email : rsilau#gmail.com
Phone : お買い得アナスイ ミロード大壳り出しランキング
Message : Shoppers takes the boast on bag
お買い得アナスイ ミロード大壳り出しランキング http://www.frkapaun.org/dyqfmnwg/ysl-annasuixmraAekm.asp
Add a hidden field to your form:
<input type="hidden" value="0" id="botcheck" name="botcheck" />
Then with jQuery set the value to 1:
$("#botcheck").val("1");
Then server-side check the value of $_POST["botcheck"].
You might want to check if your form is submitted using ajax:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Process form here
}
For further explanation

Categories