jQuery Uncaught SyntaxError: Unexpected identifier - javascript

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

Related

PHP echo in specific DIV on contact form

I'm working on a Bootstrap contact form with validation, the problem is I cannot get the PHP echo response to show on a specific DIV, after the form is sent, browser loads my contact.php file with the response. Is there any way to show the response on #success_message DIV on the same HTML? Here's my HTML:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Bootstrap 3 Contact form with Validation</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css'>
<link rel='stylesheet prefetch' href='http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<form class="well form-horizontal" action="php/contacto.php" method="post" id="contact_form">
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label">Tu nombre</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="first_name" placeholder="¿Como te llamas?" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" >Tu apellido</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="last_name" placeholder="Tu apellido" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="tucorreo#mail.com" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Teléfono</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="phone" placeholder="(55)1234-5678" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Tu comentario</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea rows="4" class="form-control" name="comment" placeholder="¡Cuéntanos como podemos ayudarte!"></textarea>
</div>
</div>
</div>
<!-- Success message -->
<div class="alert alert-success" role="alert" id="success_message">¡Listo!<i class="glyphicon glyphicon-thumbs-up"></i> Tu mensaje fue enviado, en breve nos pondremos en contacto contigo.</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<button type="submit" class="btn btn-warning" >Enviar <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.4.5/js/bootstrapvalidator.min.js'></script>
<script src="js/index.js"></script>
</body>
Here's my JS:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: '¡Queremos saber tu nombre!'
}
}
},
last_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Por favor, dinos tu apellido'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Necesitamos una dirección de correo donde contactarte'
},
emailAddress: {
message: 'Tu dirección de correo no es válida'
}
}
},
phone: {
validators: {
notEmpty: {
message: 'Por favor, proporcionanos tu teléfono'
},
phone: {
country: 'MX',
message: 'Incluye un número de teléfono válido de 10 dígitos'
}
}
},
comment: {
validators: {
stringLength: {
min: 10,
max: 200,
message:'Please enter at least 10 characters and no more than 200'
},
notEmpty: {
message: 'Please supply a description of your project'
}
}
}
}
})
.on('success.form.bv', function(e) {
$('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
$('#contact_form').data('bootstrapValidator').resetForm();
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
And my PHP:
$EmailFrom = "contacto#tuka.mx";
$EmailTo = "manuel#tuka.mx";
$Subject = "Nuevo comentario en el website";
$first_name = Trim(stripslashes($_POST['first_name']));
$last_name = Trim(stripslashes($_POST['last_name']));
$email = Trim(stripslashes($_POST['email']));
$phone = Trim(stripslashes($_POST['phone']));
$comment = Trim(stripslashes($_POST['comment']));
// prepare email body text
$Body = "";
$Body .= "Nombre: ";
$Body .= $first_name;
$Body .= "\n";
$Body .= "Apellido: ";
$Body .= $last_name;
$Body .= "\n";
$Body .= "E-mail: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Teléfono: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Comentario: ";
$Body .= $comment;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
echo "<h2>¡Gracias! Recibimos tu mensaje</h2>";
}
else{
echo "<h2>Lo sentimos, hubo un error, inténtalo nuevamente</h2>";
}
?>
I have already uploaded it here, if you want to see it working:
http://tuka.mx/beta/contacto/index.html
The first parameter for .on() method must be event.
Here
.on('success.form.bv', function(e) {
Must be:
.on('submit', function(e) {
Looks something was wrong on JS, here's a solution:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function(validator, form, submitButton) {
$('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
$('#contact_form').data('bootstrapValidator').resetForm();
var bv = form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post(form.attr('action'), form.serialize(), function(result) {
console.log(result);
}, 'json');
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: '¡Queremos saber tu nombre!'
}
}
},
last_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Por favor, dinos tu apellido'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Necesitamos una dirección de correo donde contactarte'
},
emailAddress: {
message: 'Tu dirección de correo no es válida'
}
}
},
phone: {
validators: {
notEmpty: {
message: 'Por favor, proporcionanos tu teléfono'
},
phone: {
country: 'MX',
message: 'Incluye un número de teléfono válido de 10 dígitos'
}
}
},
comment: {
validators: {
stringLength: {
min: 10,
max: 200,
message:'Please enter at least 10 characters and no more than 200'
},
notEmpty: {
message: 'Please supply a description of your project'
}
}
}
}
})
});

Working contact form but doesnt show up alert message

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...

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

Missing Variables in Contact Form Using Ajax and PHP

I have a contact form on a landing page that I want to send through with AJAX & PHP but for some reason, the variables are not passing. I am getting the email but the variables are blank. You can go to removed to see the text site, it's not set up with the database on this site though, so if you try to click through nothing will happen.
Does anyone have any idea what could be causing my form to not cooperate?
The HTML
<form role="form" id="form" name="form" action="submit.php" method="post">
<div class="form-group has-feedback">
<input type="text" class="form-control input-lg" id="name" name="name" placeholder="Full Name" />
<span class="help-block" style="display: none;">Please enter your full name.</span>
</div>
<div class="form-group has-feedback">
<input type="tel" class="form-control input-lg optional" id="phone" name="phone" placeholder="Phone (Optional)"/>
<span class="help-block" style="display: none;">Please enter a valid phone number.</span>
</div>
<div class="form-group has-feedback">
<input type="email" class="form-control input-lg" id="email" name="email" placeholder="Email" />
<span class="help-block" style="display: none;">Please enter a valid email address.</span>
</div>
<div class="form-group has-feedback">
<textarea rows="5" cols="30" class="form-control input-lg" id="message" name="message" placeholder="Message" ></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group has-feedback">
<label>
<input type="checkbox" class="form-control input-sm optional" id="newsletter" name="newsletter" checked="checked">
Opt-in to our newsletters to stay up-to-date with the latest information. </label>
<span class="help-block" style="display: none;">Would you like to sign up for our newsletter?</span>
</div>
<div class="form-group has-feedback">
<button type="submit" id="feedbackSubmit" class="btn btn-success btn-lg pull-right" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Submit</button>
</div>
</form>
The Script
//*Form*//
$('document').ready(function(){
$('#form').validate({
rules:{
"name":{
required:true,
maxlength:40
},
"phone":{
required:false
},
"email":{
required:true,
email:true,
maxlength:100
},
"message":{
required:false
},
"newsletter":{
required:false
}},
messages:{
"name":{
required:"This field is required"
},
"phone":{
required:"This field is required"
},
"email":{
required:"This field is required",
email:"Please enter a valid email address"
},
"message":{
required:"This field is required"
},
"newsletter":{
required:"This field is required"
}},
submitHandler: function(form){
$.ajax ({
type: "POST",
url: "submit.php",
dataType: "json",
data:{"name":$("#name").text(),"phone":$("#phone").text(),"email":$("#email").text(),"message":$("message").text(),"newsletter":$("#newsletter").checked},
target: '#preview',
success: function(Result) {
alert(Result[0]);
$('#formbox').slideUp('fast');
$('#success').html();
$('#success').show();
},
failure: function (arg1, arg2) {
alert(arg1 + '\n\n' + arg2);
},
error: function (Result, Error, arg3, arg4) {
alert(Result + '\n\n' + Error + '\n\n' + arg3 + '\n\n' + arg4);
}
});
}
});
});
</script>
The PHP
<?php
require_once 'db.php';
header('Content-Type: application/json');
/*
$checkemail = $_POST['email'];
if (filter_var($checkemail, FILTER_VALIDATE_EMAIL)) { echo ""; }
else { die ("Invalid email, form processing has not completed.");
}
*/
// check email validity. clean name, phone, and message.
$name = htmlspecialchars(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING));
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$phone = htmlspecialchars(filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING));
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$newsletter = htmlspecialchars(filter_input(INPUT_POST, 'newsletter', FILTER_SANITIZE_STRING));
// commit to database
require_once 'db.php';
$stmt = $pdo->prepare("INSERT INTO contact (name, phone, email, message, newsletter) VALUES (?,?,?,?,?)");
$stmt->bindParam(1, $name, PDO::PARAM_STR, 50);
$stmt->bindParam(3, $phone, PDO::PARAM_STR, 50);
$stmt->bindParam(2, $email, PDO::PARAM_STR, 50);
$stmt->bindParam(4, $message);
$stmt->bindParam(5, $newsletter, PDO::PARAM_STR, 64);
$pdo->beginTransaction();
$stmt->execute();
$pdo->commit();
//form email
$today = date("Y-m-j");
$body = "";
$body .= "Name: $name\n";
$body .= "Email: $email\n";
$body .= "Phone: $phone\n";
$body .= "Message: $message\n";
$body .= "Newsletter: $newsletter\n";
//send email 'change me to clients address'
mail("angela#etvsoftware.com","Dogwood Hills Gun Club Contact Form",$body,"angela#etvsoftware.com");
$stmt = null;
$pdo = null;
#What we say when everything goes right
$result = array(
"message" => "Your message has been sent. We will respond to you as soon as possible."
);
print json_encode($result);
?>
Instead of:
data:{"name":$("#name").text(),"phone":$("#phone").text(),"email":$("#email").text(),"message":$("message").text(),"newsletter":$("#newsletter").checked}
You should consider something cleaner and more flexible using serialize() like that:
data: $('#form').serialize()
This will send all the form fields in the POST request with your ajax call. If this is not working, Please try to var_dump($_POST) to make sure what you are getting.

Categories