Working contact form but doesnt show up alert message - javascript

This is my website: http://bbb.antalyabalikcilik.com.tr/contact-us.html
I have a contact form. I get emails to my email address but the form doesn't show up after email sending 'THANK YOU' alert.
html code:
<!-- contact form -->
<div class='grid_col grid_col_8'>
<div class='ce clearfix'>
<h3 class="ce_title">Drop us a line</h3>
<div>
<div role="form" class="cf" id="cf-f16-p10-o1" lang="en-US" dir="ltr">
<div class="screen-reader-response"></div>
<form action="email.php" method="post" class="cf-form contact-form" novalidate="novalidate">
<p>Name*
<br />
<span class="cf-form-control-wrap your-name"><input type="text" name="name" value="" size="107" class="cf-form-control cf-text cf-validates-as-required" aria-required="true" aria-invalid="false" />
</span>
</p>
<p>Email*
<br />
<span class="cf-form-control-wrap your-email"><input type="email" name="email" value="" size="107" class="cf-form-control cf-text cf-email cf-validates-as-required cf-validates-as-email" aria-required="true" aria-invalid="false" />
</span>
</p>
<p>Message
<br />
<span class="cf-form-control-wrap your-message"><textarea name="message" cols="107" rows="8" class="cf-form-control cf-textarea" aria-invalid="false"></textarea>
</span>
</p>
<p>
<input type="submit" value="Gönder" class="cf-form-control cf-submit" />
</p>
<div class="cws_msg_box error-box clearfix">
<div class="icon_section"><i class="fa fa-exclamation"></i></div>
<div class="content_section">
<div class="msg_box_title">Error box</div>
<div class="msg_box_text"></div>
</div>
</div>
</form>
<div class="email_server_responce"></div>
</div>
</div>`enter code here`
</div>
</div>
<!-- / conatct form -->
email.php
<?php
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "mail.xxx.com."; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "xxx#xxx.com"; // SMTP username
$mail->Password = "123456789"; // SMTP password
$mail->From = "xxx#xxx.com";
$mail->FromName = "www.xxx.com";
$mail->AddAddress("xxx#hotmail.com");
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "received from website email";
$mail->Body = $message;
$mail->AltBody = $message;
$content = '<div style="background: #eee; padding: 10px; font-size: 14px; font-family: comic sans ms">
İsim : '.$name.'<br />
Email : '.$email.'<br />
Mesaj : '.$message.'</div>';
$mail->MsgHTML($content);
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
js code:
/* contact form */
if (jQuery(".contact-form").length) {
/**/
/* contact form */
/**/
/* validate the contact form fields */
jQuery(".contact-form").each(function(){
jQuery(this).validate( /*feedback-form*/{
onkeyup: false,
onfocusout: false,
errorElement: 'p',
errorLabelContainer: jQuery(this).find('.msg_box_text'),
rules:
{
name:
{
required: true
},
email:
{
required: true,
email: true
},
message:
{
required: true
},
verify: {
required: true,
remote: {
url: 'php/check-capcha.php',
type: "post",
data:
{
code: function()
{
return jQuery('.verify').val();
}
}
}
}
},
messages:
{
name:
{
required: 'Please enter your name',
},
email:
{
required: 'Please enter your email address',
email: 'Please enter a VALID email address'
},
message:
{
required: 'Please enter your message'
},
verify: {
required: 'Please enter Captcha',
remote: "Please enter a VALID Captcha"
}
},
invalidHandler: function()
{
jQuery(this).find(".cws_msg_box.error-box").slideDown('fast');
jQuery("#feedback-form-success").slideUp('fast');
},
submitHandler: function(form)
{
jQuery(form).find(".cws_msg_box.error-box").slideUp('fast');
var $form = jQuery(form).ajaxSubmit();
submit_handler($form, jQuery(form).parent().children(".email_server_responce") );
}
});
})
/* Ajax, Server response */
var submit_handler = function (form, wrapper){
var $wrapper = jQuery(wrapper); //this class should be set in HTML code
$wrapper.css("display","block");
var data = {
action: "email_server_responce",
values: jQuery(form).serialize()
};
//send data to server
jQuery.post("email.php", data, function(s_response) {
s_response = jQuery.parseJSON(s_response);
if(s_response.info == 'success'){
$wrapper.addClass("message message-success").append('<div class="cws_msg_box success-box clearfix"><div class="icon_section"><i class="fa fa-thumbs-up"></i></div><div class="content_section"><div class="msg_box_title">Success!</div><div class="msg_box_text">Your message was successfully delivered.</div></div></div>');
$wrapper.delay(5000).hide(500, function(){
jQuery(this).removeClass("message message-success").text("").fadeIn(500);
$wrapper.css("display","none");
});
jQuery(form)[0].reset();
} else {
$wrapper.addClass("cws_msg_box error-box clearfix").append("<div class='icon_section'><i class='fa fa-exclamation'></i></div><div class='content_section'><div class='msg_box_title'>Server fail!</div><div class='msg_box_text'><p> Please try again later!</p></div></div>");
$wrapper.delay(5000).hide(500, function(){
jQuery(this).removeClass("cws_msg_box error-box clearfix").text("").fadeIn(500);
$wrapper.css("display","none");
});
}
});
return false;
}
}
/**/
What is wrong?Please help me...

Related

jQuery Uncaught SyntaxError: Unexpected identifier

Please I'm getting uncaught SyntaxError: Unexpected identifier in line 5 email subject: { also the code is not working. What is the problem?
<script>
jQuery(document).ready(function($){
$("#contactform").validate({
rules: {
email subject: {
required: true,
},
email: {
required: true,
email: true
},
message:{
required: true,
}
},
messages: {
email subject: {
required: "Please select a valid email subject.",
},
email: {
required: "Please your valid email address",
email: "Please your valid email address"
},
message: {
required: "Please enter your message",
}
}
});
});
</script>
EDIT 1: I've changed email address to email_address and also in html the problem has gone but the jquery validation is not working ...
Here is my full code:
<?php
require_once 'core/init.php';
include 'includes/head.php';
$hasError = false;
$sent = false;
if (isset($_POST['submitform'])) {
$email = trim($_POST['email']);
$message = trim(htmlspecialchars($_POST['message'], ENT_QUOTES));
$fieldsArray = array(
'email' => $email,
'message' => $message
);
$errorArray = array();
foreach($fieldsArray as $key => $val) {
switch ($key) {
case 'message':
if(empty($val)) {
$hasError = true;
$errorArray[$key] = ucfirst($key) . " field was left empty.";
}
break;
case 'email':
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$hasError = true;
$errorArray[$key] = "Invalid Email Address entered";
}else{
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
}
break;
}
}
if($hasError !== true) {
$to = "example#gmail.com";
$subject = "Message ";
$msgcontents = "Email: $email<br>Message: $message";
$headers = "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers .= "From: $name <$email> \r\n";
$mailsent = mail($to, $subject, $msgcontents, $headers);
if($mailsent) {
$sent = true;
unset($email);
unset($message);
}
}
}
?>
<div class="container-fluid">
<h4 class="text-left" id="backcolor" style="margin-top:205px;">
<a style="text-decoration:none;" href="customerservice.php">Customer Service</a> > Contact us</h4>
<h2>Contact us</h2>
<h4>Contact Us</h4>
<br>
<p>Please visit our Customer Service page, which may provide the answer you are looking for.</p>
<br>
<p>If there are ways that we can better delight you, please contact us by completing the form below.</p>
<div class="row">
<form id="contactform" method="post" novalidate>
<?php
if($sent == true) {
echo "<h2 class='success'>Thanks, your message has been sent</h2>";
} elseif($hasError == true) {
echo '<ul class"errorlist">';
foreach($errorArray as $key => $val){
echo "<li>" . ucfirst($key) . " field error - $val</li>";
}
echo '<ul>';
}
?>
<div class="form-group col-md-6">
<label for="email_subject"><span>* </span>Email Subject</label>
<select class="form-control" id="email_subject" name="email_subject">
<option >Select Email Subject</option>
<option >My Account</option>
<option >Orders</option>
<option >Product Information Questions</option>
<option >Website Technical Questions</option>
<option >Suggestions or Comments</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="form-group col-md-6">
<label for="message"><span>* </span>Message</label>
<textarea id="message" name="message" value="<?= (isset($message) ? $message : "");?>" class="form-control" rows="10"
style="background-color:#EEEEEE; border:none;"></textarea>
</div>
</div>
<br>
<div class="row">
<div class="form-group col-md-6">
<label for="email"><span>* </span>Your Email Address</label>
<input type="email" name="email" value="<?= (isset($email) ? $email : "");?>" class="form-control"
id="email" style="background-color:#EEEEEE;">
</div>
</div>
<br>
<div class="form-group">
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg" name="submitform">
</div><div class="clearfix"></div>
</form>
</div>
<script>
jQuery(document).ready(function($){
$("#contactform").validate({
rules: {
email_subject: {
required: true,
},
email: {
required: true,
email: true
},
message:{
required: true,
}
},
messages: {
email_subject: {
required: "Please select a valid email subject.",
},
email: {
required: "Please your valid email address",
email: "Please your valid email address"
},
message: {
required: "Please enter your message",
}
}
});
});
</script>
And in the head.php:
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
Please help !!!
You cannot use spaces in object keys as you did
email subject: {
required: true
}
Instead wrap key in quotes like
"email subject": {
required: true
}
or use a key without spaces.
email_subject: {
required: true
}
Dont give spaces in object keys
Use this-
<script>
jQuery(document).ready(function($){
$("#contactform").validate({
rules: {
email_subject: {
required: true,
},
email: {
required: true,
email: true
},
message:{
required: true,
}
},
messages: {
email_subject: {
required: "Please select a valid email subject.",
},
email: {
required: "Please your valid email address",
email: "Please your valid email address"
},
message: {
required: "Please enter your message",
}
}
})}
});
</script>
There should not be any space for the objectproperty name.
email subject: {
required: true,
},
Replace email subject by email_subject or anything meanigful name without space.
Like the answer above my answer, you might change your email subject instead email_subject cause identifier can't use space on it, and you need change identifier on your input form, like these <input type="email" id="email_subject" name="email_subject">
Here let me help you with your code
<script>
jQuery(document).ready(function($){
$("#contactform").validate({
rules: {
email_subject: {
required: true,
},
email: {
required: true,
email: true
},
message:{
required: true,
}
},
messages: {
email_subject: {
required: "Please select a valid email subject.",
},
email: {
required: "Please your valid email address",
email: "Please your valid email address"
},
message: {
required: "Please enter your message",
}
}
});
});
</script>
And do not forget on your form input, you need changed name and id into email_subject

Contact form doesn't validate inside bootstrap modal

So I have made a contact form using the example at https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form which works fine when placed on a page, however when I place it inside a bootstrap popup modal, the validator doesn't work. If all fields are empty and submit button hit, it will say 'message sent' even though it did not send, and if you fill in the fields it will still send and give success message also.
Also, if I hit the button to open modal as soon as page loads but before the script has loaded, it will work, so it's obviously because the modal is not visible when the validator script loads, so it misses it.
If anyone has some answers it would be super helpful as I'm pretty new to PHP and JS!
Here is my modal HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header"><button aria-label="Close" class="close"
data-dismiss="modal" type="button"><span aria-hidden=
"true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form action="../contact.php" id="contact-form" method="post" name=
"contact-form">
<div class="messages"></div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_name">Firstname *</label>
<input class="form-control" data-error="Firstname is required." id="form_name"
name="name" placeholder="Please enter your first name" required="required"
type="text">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_email">Email *</label> <input class=
"form-control" data-error="Valid email is required." id="form_email" name=
"vemail" placeholder="Please enter your email" required="required" type=
"email">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_message">Message *</label>
<textarea class="form-control" data-error="Please,leave us a message." id=
"form_message" name="message" placeholder="Please enter your message" required=
"required" rows="4"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12"><input class="btn btn-success btn-send" type="submit"
value="Send message"></div>
</div>
</form>
</div>
</div>
<!-- /.modal-content --></div>
<!-- /.modal-dialog --></div>
<!-- /.modal -->
</body>
</html>
This is my PHP file
<?php
// configure
$from = '<mail#myemail.net>';
$sendTo = 'Demo contact form <mail#myemail.net>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'vemail' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
$email = ($_POST["vemail"]);
$subject2 = 'Thank you for contacting support.';
$msg = "Thank you for contacting Support. We have received your contact form and will be in contact as soon as possible";
$headers = 'Reply-To: mail#myemail.net' . "\r\n" ;
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($email, $subject2, $msg, $headers) && mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
?>
And JS
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "../contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
Put your ajax call inside the validation process and use submitHandler.
This answer by #Sparky might save your day https://stackoverflow.com/a/15625824/6952155
Please refer to this and edit to suit in your code.
$(document).ready(function () {
$("#contactform").validate({
ignore: ":hidden",
rules: {
name: {
required: true,
minlength: 3
},
cognome: {
required: true,
minlength: 3
},
subject: {
required: true
},
message: {
required: true,
minlength: 10
}
},
submitHandler: function (form) {
alert('valid form submission'); // for demo
$.ajax({
type: "POST",
url: "formfiles/submit.php",
data: $(form).serialize(),
success: function () {
$(form).html("<div id='message'></div>");
$('#message').html("<h2>Your request is on the way!</h2>")
.append("<p>someone</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='images/ok.png' />");
});
}
});
return false; // required to block normal submit since you used ajax
}
});
});
Ondrej here, author of the tutorial on Bootstrapious.
I have just found out that there was an error in Bootstrap validator and it was not working correctly in combination with the Bootstrap modal.
The solution is downloading the latest version from https://github.com/1000hz/bootstrap-validator, currently 0.11.5.
Best,
Ondrej

Contact form PHPMailer sending button is stuck loading

I'm having trouble with my contact form. I'm using the code from jon bake. However I can't get it to work, it's not sending the mail (or I'm not receiving it) and I don't even get the "success" message after pressing 'send'. This is how it looks in the 'console'.
I also get
HTTP500 : Server Error - Failed to execute request because the server encountered an unexpected condition .
( XHR ) : POST -
from console.
HTML
<form role="form" id="feedbackForm" method = "post" data-toggle="validator" data-disable="false">
<div class="form-group">
<label class="control-label" for="name">Name *</label>
<div class="input-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter your name" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter your name.</span>
</div>
<div class="form-group">
<label class="control-label" for="phone">Phone</label>
<input type="tel" class="form-control optional" id="phone" name="phone" placeholder="Enter your phone (Optional)"/>
<span class="help-block" style="display: none;">Please enter a valid phone number.</span>
</div>
<div class="form-group">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<label class="control-label" for="email">Email Address *</label>
<div class="input-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<label class="control-label" for="message">Message *</label>
<div class="input-group">
<textarea rows="5" cols="30" class="form-control" id="message" name="message" placeholder="Enter your message" required></textarea>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LfIxCQTAAAAAK7ZBb9liJNpaebx12UbmOfiqtl9"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
</div>
<span class="help-block" style="display: none;">Please enter a the security code.</span>
<button type="submit" id="feedbackSubmit" class="btn btn-primary btn-lg" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Send Feedback</button>
</form>
</div><!--/span-->
</div><!--/row-->
<hr>
</div><!--/.container-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="assets/vender/intl-tel-input/js/intlTelInput.min.js"></script>
<script src="assets/js/contact-form.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
The contact-form.js
(function () {
//using regular expressions, validate email
var contactFormUtils = {
isValidEmail: function (email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9] {2,4})+$/;
return regex.test(email);
},
//if no form errors, remove or hide error messages
clearErrors: function () {
$('#emailAlert').remove();
$('#feedbackForm .help-block').hide();
$('#feedbackForm .form-group').removeClass('has-error');
},
//upon form clear remove the checked class and replace with unchecked class. Also reset Google ReCaptcha
clearForm: function () {
$('#feedbackForm .glyphicon').removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
$('#feedbackForm input,textarea').val("");
grecaptcha.reset();
},
//when error, show error messages and track that error exists
addError: function ($input) {
var parentFormGroup = $input.parents('.form-group');
parentFormGroup.children('.help-block').show();
parentFormGroup.addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$(document).ready(function() {
if ($("#phone").intlTelInput) {
$("#phone").intlTelInput({validationScript: "assets/vender/intl-tel- input/js/isValidNumber.js"});
$(".intl-tel-input.inside").css('width', '100%');
}
$("#feedbackSubmit").click(function() {
var $btn = $(this);
$btn.button('loading');
contactFormUtils.clearErrors();
//do a little client-side validation -- check that each field has a value and e-mail field is in proper format
//use bootstrap validator (https://github.com/1000hz/bootstrap-validator) if provided, otherwise a bit of custom validation
var $form = $("#feedbackForm"),
hasErrors = false;
if ($form.validator) {
hasErrors = $form.validator('validate').hasErrors;
} else {
$('#feedbackForm input,#feedbackForm textarea').not('.optional').each(function() {
var $this = $(this);
if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) {
hasErrors = true;
contactFormUtils.addError($(this));
}
});
var $email = $('#email');
if (!contactFormUtils.isValidEmail($email.val())) {
hasErrors = true;
contactFormUtils.addError($email);
}
var $phone = $('#phone');
if ($phone.val() && $phone.intlTelInput && !$phone.intlTelInput("isValidNumber")) {
hasErrors = true;
contactFormUtils.addError($phone.parent());
}
}
//if there are any errors return without sending e-mail
if (hasErrors) {
$btn.button('reset');
return false;
}
//send the feedback e-mail
$.ajax({
type: "post",
url: "../../library/sendmail.php",
data: $form.serialize(),
success: function(data) {
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
},
complete: function() {
$btn.button('reset');
}
});
return false;
});
$('#feedbackForm input, #feedbackForm textarea').change(function () {
var checkBox = $(this).siblings('span.input-group-addon').children('.glyphicon');
if ($(this).val()) {
checkBox.removeClass('glyphicon-unchecked').addClass('glyphicon-check').css({color: 'green'});
} else {
checkBox.removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
}
});
});
})();
And the PHP
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($messsage) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $messsage)));
}
/**
* Pulls posted values for all fields in $fields_req array.
* If a required field does not have a value, an error response is given.
*/
function constructMessageBody () {
$fields_req = array("name" => true, "email" => true, "message" => true);
$message_body = "";
foreach ($fields_req as $name => $required) {
$postedValue = $_POST[$name];
if ($required && empty($postedValue)) {
errorResponse("$name is empty.");
} else {
$message_body .= ucfirst($name) . ": " . $postedValue . "\n";
}
}
return $message_body;
}
header('Content-type: application/json');
//do Captcha check, make sure the submitter is not a robot:)...
$url = 'https://www.google.com/recaptcha/api/siteverify';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query(array('secret' => '6LfIxCQTAAAAABhWEJuLVdzE9m_-cwbBs9lM1xVi', 'response' => $_POST["g-recaptcha-response"]))
)
);
$context = stream_context_create($opts);
$result = json_decode(file_get_contents($url, false, $context, -1, 40000));
if (!$result->success) {
errorResponse('reCAPTCHA checked failed!');
}
//attempt to send email
$messageBody = constructMessageBody();
require_once './vender/php_mailer/PHPMailerAutoload.php';
include_once './vender/php_mailer/class.phpmailer.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPDebug = 2
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "gmail.com";
$mail->Password = "password";
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress "gmail.com";
$mail->Subject = "Contact Form";
$mail->Body = $message_body;
//try to send the message
if($mail->send()) {
echo json_encode(array('message' => 'Your message was successfully submitted.'));
} else {
errorResponse('An expected error occured while attempting to send the email: ' . $mail->ErrorInfo);
}
?>
I'm very new to JavaScript and PHP so maybe I've missed something but I've tried to find a solution on Google but not been able to find one.
I hope I've made myself clear, thanks.

display user end error before submitting a form

I have a form through which i wish to add values in database. it is working fine, for validation i have added server end validation, but the errors if any get displayed after the form has been submitted, i wish to use user end validation in a way that if a user does not enter a field, is not entering a proper format or the password do not match, the error should get displayed simultaneously i.e before hitting the submit button. Can anyone tell how it can be done
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email =$_POST["email"];
}
if (empty($_POST["password"]))
{
$pswrdErr = "password is required";
}
else
{
$password = $_POST["password"];
}
if ($_POST["password"]!=$_POST["retype_password"])
{
$pswrdErr = "password does not match";
}
else
{
$password = $_POST["password"];
}
//insert query to add values in database
}
?>
<form name="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" >
<input type="text" placeholder="Name" name="name"/>
<input type="email" placeholder="Email" name="email"/>
<input type="password" placeholder="Password" name="password"/>
<input type="password" placeholder="Retype Password" name="retype_password"/>
<button name ="submit" value = "submit" class="btn btn-greensea b-0 br-2 mr-5">Register</button>
</form>
You can try this
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email =$_POST["email"];
}
if (empty($_POST["password"]))
{
$pswrdErr = "password is required";
}
else
{
$password = $_POST["password"];
}
if ($_POST["password"]!=$_POST["retype_password"])
{
$pswrdErr = "password does not match";
}
else
{
$password = $_POST["password"];
}
//insert query to add values in database
}
?>
<form name="form" id="register-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" >
<input type="text" placeholder="Name" name="name"/>
<input type="email" placeholder="Email" name="email"/>
<input type="password" placeholder="Password" name="password" id="password"/>
<input type="password" placeholder="Retype Password" name="retype_password" id="retype_password"/>
<button name ="submit" value = "submit" class="btn btn-greensea b-0 br-2 mr-5">Register</button>
</form>
<script>
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#register-form").validate({
rules: {
name: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5,
},
retype_password: {
equalTo :'#password'
}
},
messages: {
name: "Please enter your name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
</body>
</html>
use jquery code for client side validation
$(form).submit(function(e){
if($("input[name='name']").val()=="")
{
e.preventDefault();//this will stop form from submitting
//show msg name is required
}
});

Bootstrap Contact Form with jQuery Validation and AJAX

I have a simple bootstrap contact form that I'm trying to implement with AJAX and jQuery validation. I feel like I'm pretty close but there are a few things that I can't get to work quite right. The forms validate according to input (ideally I'd like the phone number to be validated as digits; however, I'm new to contact form validation), but the contact form will still send even if the answers are not correct. In addition, the success box will always pop up after the form submits ... I'd like the form to not send if it is filled out incorrectly, and an error box to appear instead of the success. In addition, the email sends through the body of the message, but none of the variables get sent over. So the body of my message looks like:
Name:
Email:
Phone:
Message:
With no variable appear after each.
I know this may be something simple but I'm very new to form validation and I can't figure it out for the life of me.
Here's the HTML for the form:
<div class="form-group wow fadeInRight" data-wow-delay="1s">
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" class="form-control" id="name" name="name" placeholder="Name" />
</div>
</div>
</div>
<div class="form-group wow fadeInRight" data-wow-delay="1.1s">
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="text" class="form-control" id="email" name="email" placeholder="Email" />
</div>
</div>
</div>
<div class="form-group wow fadeInRight" data-wow-delay="1.2s">
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>
<input type="text" class="form-control" id="phone" name="phone" placeholder="Phone" />
</div>
</div>
</div>
<div class="form-group wow fadeInRight" data-wow-delay="1.3s">
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea name="message" class="form-control " rows="4" cols="78" placeholder="Enter your message here."></textarea>
</div>
</div>
</div>
<div id="success"></div>
<div class="row wow fadeInUp" data-wow-delay="1.3s">
<div class="form-group col-xs-12">
<div class="contact-btns">
<input type="submit" class="submit-button" value="Submit" name="submit">
<input type="reset" class="clear-buttom" value="Clear" name="clear">
</div>
</div>
</div>
</form>
Here's the PHP:
$status = array(
'type' => 'success',
'message' => 'Email sent!'
);
$val = $_POST['val'];
$toemail = 'myemail#gmail.com';
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$msg = $_POST['message'];
$subject = 'Thelliotgroup Information Request';
$headers = "From: Thelliotgroup Website :: " . $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<b>Name: </b>" . $name . "<br>";
$message .='<b>Email: </b>' . $email . "<br>";
$message .='<b>Phone: </b>' . $phone . "<br>";
$message .='<b>Message: </b>' . $msg;
$success = mail($toemail, $subject, $message, $headers);
echo json_encode($status);
die
Here's the AJAX and jQuery:
var form = $('.contact');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function (data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
}, 'json');
return false;
});
$.validator.setDefaults({
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "email.php",
data: {'val': $(".contact").serializeJSON()}
}).done(function (data) {
alert(data);
});
}
});
$(".contact").validate(
{rules:
{name: "required",
email: {required: true, email: true},
phone: "required",
message: {required: true, maxlength: 300
}},
errorClass: "error",
highlight: function (label) {
$(label).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function (label) {
label
//.text('Seems Perfect!').addClass('valid')
.closest('.form-group').addClass('has-success');
}
});
I'd really appreciate any help you guys could give me to get this working properly.
Edit
Here's the new jQuery and AJAX code:
$(document).ready(function() {
var form = $(this);
var post_url = form.attr('action');
$('.contact').validate({
rules: {
name: {
rangelength: [2,40],
required: true
},
email: {
rangelength: [2,40],
email: true,
required: true
},
phone: {
rangelength: [7,10],
required: true
},
message: {
minlength: 30,
required: true
},
errorClass:"error",
highlight: function(label) {
$(label).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function(label) {
label
.closest('.form-group').addClass('has-success');
}
},
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'email.php',
data: $(form).serialize(),
success: function(msg) {
$('.sent').fadeIn().fadeOut(5000);
}
});
return false;
}
});
});
Now I just need to figure out how to make it so that:
<div class="status alert alert-success" style="display: none"></div>
Which is located directly above the form, will fade in once the form is submitted.
I can't get it to work.
Thanks,
Brennan
I do not understand why you're doing a .post() (ajax) inside of a jQuery submit handler function while at the exact same time you have .ajax() inside of the plugin's submitHandler function. I don't get it. Why are you using ajax twice?
I think it's best that you remove this entire function...
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
Because it is interfering with the plugin's submitHandler function.
Use the submitHandler to fire code upon the button click when the form is valid. This is where any ajax would belong.
EDIT:
You've put errorClass, highlight and success inside the rules option...
rules: {
name: {
....
},
email: {
....
},
phone: {
....
},
message: {
....
},
errorClass:"error",
highlight: function(label) {
....
},
success: function(label) {
....
}
},
This is wrong. errorClass, highlight and success are siblings of the rules and submitHandler options.
Also, when using highlight, it's best to use unhighlight along with it to undo whatever you did with highlight.
rules: {
// only your rules here
},
errorClass:"error",
highlight: function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').addClass('has-success').removeClass('has-error');
},
submitHandler: function(form) {
$.ajax({
// your options
});
return false;
}
For clearing out the form within the Ajax success option...
$('#myform').validate().resetForm(); // reset validation
form[0].reset(); // clear out the form data

Categories