I have live validation for forms its working fine But AJAX functions are not working. whenever I click submit its directly redirected to the mailer.php without ajax function. I tried all the ways to fix but no luck. Someone please help me out.
When I click submit button if all the fields are validated it should go to AJAX form and submit.
$(function validateForm(){
$("#cname").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter the Name"
});
$("#cnumber").validate({
expression: "if (VAL.match(/^[0-9\.\-\/]+$/)) return true; else return false;",
message: "Please enter a valid Phone number"
});
$("#csubject").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter the Subject"
});
$("#cemail").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\#[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Please enter a valid Email ID"
});
$("#cmessage").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter the Message"
});
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).validated(function(e){
$(formMessages).addClass('wait').text("please wait...");
e.preventDefault();
var formData = $(form).serialize();
var action = $(this).attr('action');
$.post(action, $(form).serialize(),
function(data) {
if (data.match('success') != null) $('#ajax-contact .form-group, #ajax-contact .theme-btn').slideUp('slow');
}
)
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#cname').val('');
$('#cemail').val('');
$('#cnumber').val('');
$('#csubject').val('');
$('#cmessage').val('');
gtag('event', 'form_submission', {
'event_category': 'contact_us',
'event_label': 'success'
});
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
})
});
});
HTML
<form id="ajax-contact" method="post" action="mailer/function/smtpemail.php" class="wpcf7-form AdvancedForm" autocomplete="on">
<div class="form-group">
<input id="cname" type="text" name="cname" value="" placeholder="NAME">
</div>
<div class="form-group">
<input id="cemail" type="email" data-missing="This field is required" data-mismatch="Please include a valid email" name="cemail" value="" placeholder="EMAIL">
</div>
<div class="form-group">
<input id="cnumber" type="text" maxlength="15" name="cnumber" value="" placeholder="MOBILE">
</div>
<div class="form-group">
<input id="csubject" type="text" name="csubject" value="" placeholder="SUBJECT">
</div>
<div class="form-group">
<textarea id="cmessage" draggable="false" name="cmessage" placeholder="YOUR MESSAGE"></textarea>
</div>
<div class="form-group">
<button onclick='return validateForm()' type="submit" id="submit" class="theme-btn btn-style-four">Submit</button>
</div>
<div id="form-messages"></div>
</form>
You can use the submit function:
$("#ajax-contact").submit(function(e) {
if (!yourValidationFunction()) {
e.preventDefault();
}
});
Related
I have a 'contact us' form on our website, people fill out name, email, and message and hit send. Currently the form won't submit if I have the email validation in my code.
Here is HTML form code:
<form role="form" id="feedbackForm">
<div class="form-group">
<label class="control-label" for="name">Full 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="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="reason">Contact Reason *</label>
<select name="reason" class="form-control" required>
<option value="General Inquiry">General Inquiry</option>
<option value="Schedule Appointment">Schedule Appointment</option>
<option value="Report Issue">Report Issue</option>
<option value="Provide Feedback">Provide Feedback</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="message">Message *</label>
<div class="input-group">
<textarea rows="5" 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="mykey"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
<button type="submit" id="feedbackSubmit" class="btn btn-success btn-lg" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Send Feedback
</button>
</div>
</form>
and here's the jquery code:
(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() {
$("#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);
}
}
//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: "php/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: ''});
}
});
});
})();
When I remove this bit of code that validates if the email is in correct format then the form sends to my email right away.
var $email = $('#email');
if (!contactFormUtils.isValidEmail($email.val())) {
hasErrors = true;
contactFormUtils.addError($email);
}
Which in turn leads to this bit, I believe :
if (hasErrors) {
$btn.button('reset');
return false;
}
if I comment out 'return false;' then it sends the form
I can't find what part of the email validation prevents the form from submitting?
Maybe you have another element with id="email" somewhere.
Maybe try:
$('#feedbackForm input[type=email]').each(function() {
if (!contactFormUtils.isValidEmail(this.val())) {
hasErrors = true;
contactFormUtils.addError(this);
console.log("ERROR: Invalid email: "+this.val()+" in input "+this.attr("name"));
}
})
i have one form like this.
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
and i call one .js file for it is.
$(document).ready(function(){
$('#send_message').click(function(e){
//Stop form submission & check the validation
e.preventDefault();
// Variable declaration
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#phone').val();
var message = $('#message').val();
// Form field validation
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#phone_error').fadeIn(500);
}else{
$('#phone_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
// If there is no validation error, next to process the mail function
if(error == false){
// Disable submit button just after the form processed 1st time successfully.
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("contact-post.php", $("#contact_form").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
//If the email is sent successfully, remove the submit button
$('#submit').remove();
//Display the success message
$('#mail_success').fadeIn(500);
}else{
//Display the error message
$('#mail_fail').fadeIn(500);
// Enable the submit button again
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
and one contact-post.php file is.
<?php
include('config.php');
if (isset($_POST['submit'])) {
$name=$_POST['name'];
$mail=$_POST['email'];
$phone=$_POST['phone'];
$msg=$_POST['message'];
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
test_input($name);
$query="INSERT INTO `inquiry` (id,name,contact,email,query) values ('','$name','$phone','$mail','$msg')";
$qur=mysql_query($query);
if ($qur) {
echo 'sent';
}
else {
echo 'failed';
}
}
?>
my problem is when i refresh page it's displaying like this.
i want that all message should not display before clicking submit button.please help me.
Update (adding snippet) :
.error , .success
{
display:none;
}
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
You can do one of the following :
Set the error and success classes display to none, since they will be displayed using the fadeIn function.
.error , .success
{
display:none;
}
Or
You can hide the <div>s with jQuery on load as follows :
$(document).ready(function(){
$('.error , .success').hide();
.....
});
I guess the first solution would be a better approach since the elements will not view at all since CSS loads before JS (assuming that this is the order you are loading your files with), while in the second approach the elements will be visible until jQuery loads and hides them.
Add a style as below to hide the error/success messages.
#mail_fail, #mail_success{
display : none;
}
http://jsfiddle.net/Nvt2h/
I am using this script which sends details from input fields to my email. As you can see, there is input.error which highlights the field in red if there is an incorrect entry. However, this currently works only for Field 1 and Field 4.
How can I make this work on field 2 and 3 as well ?
<form id="contact" name="contact" action="#" method="post">
<div class="form-group">
<label for="msg">Field1:
</label>
<input name="msg" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
<label for="id">Field2:</label>
<input name="id" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
<label for="pb">Field3:
</label>
<input name="pb" type="msg" class="form-control" id="pb">
</div>
<div class="form-group">
<label for="email">Field4:</label>
<input name="email" type="email" class="form-control" id="email">
</div>
<button id="send">Submit</button>
Add a minlength attribute to those input fields
<input name="msg" type="msg" class="form-control msg" id="msg" minlength="2">
then
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function () {
//$(".modalbox").fancybox();
$("#contact").submit(function () {
return false;
});
$("#send").on("click", function () {
$('#contact input.error').removeClass('error');
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
if (mailvalid == false) {
$("#email").addClass("error");
}
var minlen = $('#contact input[minlength]').filter(function(){
return this.value.length < +$(this).attr('minlength')
}).addClass('error').length;
if (mailvalid == true && minlen == 0) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>");
$.ajax({
type: 'POST',
url: 'send.php',
data: $("#contact").serialize(),
dataType: 'jsonp',
success: function (data) {
if (data.result == true) {
$("#contact").fadeOut("fast", function () {
$(this).before("<p class='success'><strong>Thank you, your message has been sent. We will be in touch shortly.</strong></p>");
});
} else { /* if you want to handle mail send failed, put it here */
}
},
error: function (jqXHR, textStatus, errorThrown) {
// this is triggered if there's a problem getting the jsonp back from the server
}
});
}
});
});
Demo: Fiddle
Hi Could you please have a look at my HTML and function? The required field doesn't work. Any ideas why?
<form action='contact_form.php' method='post' class="contactForm">
<div class="formSecWrap">
<input type="text" class="formField" title="Name" id="name" name="name" value="" required/>
<input type="text" class="formField" title="Email" name="email" id="email" value="" required/>
<input type="text" class="formField" title="Phone" name="phone" id="phone" value="" required />
<input type="text" class="formField" title="Date & Time" name="date" id="date" value="" required/>
</div>
<div class="formSecWrap formSecWrap2">
<textarea class="textarea formField" title="Message" name="message" id="message"></textarea>
</div>
<input class="button" id="submit-form" type="submit" name="submit" value="Send Message" />
<div id="success">
</div>
</form>
And here is my function. I am not sure why it doesn't pick it up as a required fields.I have not created this form myself but was trying to work it out somehow.
Thank you
(function($){
$(document).ready(function() {
$('#submit-form').click(function(e){
e.preventDefault();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $('#name').val(),
email = $('#email').val(),
phone = $('#phone').val(),
date = $('#date').val(),
message = $('#message').val(),
data_html,
success = $('#success');
if(name == "")
$('#name').val('Please enter your name.');
if(phone == "")
$('#phone').val('Please enter your phone number.');
if(date == "")
$('#date').val('Please enter a date and time.');
if(email == ""){
$('#email').val('Your email is required.');
}else if(reg.test(email) == false){
$('#email').val('Invalid Email Address.');
}
if(message == "")
$('#message').val('Message is required.');
if(message != "" && name != "" && reg.test(email) != false) {
data_html = "name=" + name + "&email="+ email + "&message=" + message + "&phone="+ phone + "&date="+ date;
//alert(data_html);
$.ajax({
type: 'POST',
url: '../contact_form.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
success.html('<div class="alert alert-success">Message <strong>successfully</strong> sent!</div>') ;
$('#name').val('');
$('#phone').val('');
$('#email').val('');
$('#date').val('');
$('#message').val('');
}else{
success.html('<div class="alert alert-error">Message <strong>not</strong> sent! Please Try Again!</div>') ;
}
}
});
}
return false;
});
});
});
try to pass arguments to you anonymous function
(function($){
//all that code
})(jQuery);
You can try executing the anonymous function something like:
(function($){
//Your code
}.call(this));
Please create the fiddle if the problem does not get resolved
anonymous function should be called for execution:
(function($){
//your code
})(jQuery);
for calling anonymous function use () right after the function ends, and pass jQuery parameter.
Remove the first and the last lines from your javascript.
(function($){
and
});
It wraps the code into an anonymous function which isn't invoked so you don't bind the click event to the submit button.
its working fine in both firefox and chrome..
Still if does not work you can check this out
HTML form required command not working?
I am looking to make a simple form validation error message that displays under the username field.
I cannot seem to figure it out.
<form name ="myform" onsubmit="validation()">
Username: <input type ="text" name="username" /><br />
<input type ="submit" value="submit" />
<div id ="errors">
</div>
</form>
Here is my validation script:
function validation(){
if(document.myform.username.value == ""){ //checking if the form is empty
document.getElementById('errors').innerHTML="*Please enter a username*";
//displaying a message if the form is empty
}
You need to stop the submission if an error occured:
HTML
<form name ="myform" onsubmit="return validation();">
JS
if (document.myform.username.value == "") {
document.getElementById('errors').innerHTML="*Please enter a username*";
return false;
}
JavaScript
<script language="javascript">
var flag=0;
function username()
{
user=loginform.username.value;
if(user=="")
{
document.getElementById("error0").innerHTML="Enter UserID";
flag=1;
}
}
function password()
{
pass=loginform.password.value;
if(pass=="")
{
document.getElementById("error1").innerHTML="Enter password";
flag=1;
}
}
function check(form)
{
flag=0;
username();
password();
if(flag==1)
return false;
else
return true;
}
</script>
HTML
<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">
<div id="error0"></div>
<input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
controls">
<div id="error1"></div>
<input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">
<button type="submit" class="btn">Sign in</button>
</div>
</div>
</form>
I would strongly suggest you start using jQuery. Your code would look like:
$(function() {
$('form[name="myform"]').submit(function(e) {
var username = $('form[name="myform"] input[name="username"]').val();
if ( username == '') {
e.preventDefault();
$('#errors').text('*Please enter a username*');
}
});
});