I have a jQuery Ajax form that looks like this:
<form method="post" action="contact.php" class="contact-form">
<div class="contact-empty">
<input type="text" name="name" id="name" placeholder="Name *" class="txt-name" />
<input type="text" name="email" id="contact-email" placeholder="Email Address *" class="txt-email" />
<textarea rows="4" name="message" cols="60" id="message" placeholder="Message *" class="txt-message"></textarea>
<span class="btn-contact-container">
<button id="contact-submit" class="btn-contact">Submit</button>
<img src="images/loading.gif" alt="Loading..." width="62" height="62" id="contact-loading">
</span>
<span class="contact-error-field"></span>
</div>
<div class="contact-message"></div>
</form>
Here's my js that sends it:
$(document).ready(function () {
$('#contact-submit').click(function () {
$('.contact-error-field').hide();
var nameVal = $('input[name=name]').val();
var emailReg = /^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/;
var emailVal = $('#contact-email').val();
var messageVal = $('textarea[name=message]').val();
//validate
if (nameVal == '' || nameVal == 'Name *') {
$('.contact-error-field').html('Your name is required.').fadeIn();
return false;
}
if (emailVal == "" || emailVal == "Email Address *") {
$('.contact-error-field').html('Your email address is required.').fadeIn();
return false;
}
else if (!emailReg.test(emailVal)) {
$('.contact-error-field').html('Invalid email address.').fadeIn();
return false;
}
if (messageVal == '' || messageVal == 'Message *') {
$('.contact-error-field').html('Please provide a message.').fadeIn();
return false;
}
var data_string = $('.contact-form').serialize();
$('.btn-contact').hide();
$('#contact-loading').fadeIn();
$('.contact-error-field').fadeOut();
$.ajax({
type: "POST",
url: "contact.php",
data: data_string,
//success
success: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-check contact-success"></i>Your message has been sent.').fadeIn();
},
error: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-times contact-error"></i>Something went wrong, please try again later.').fadeIn();
}
}) //end ajax call
return false;
});
});
I have a subscribe form that uses the same code with just an email input and that submits fine on an iphone.
The contact form, however, gets stuck at 'Invalid email address.' when trying to submit from an iPhone even though the email you enter is correct. It works on desktop.
I've tried changing the button to a type="submit" input. Didn't change anything.
UPDATE: My regex was wrong, I replaced it with the following and it worked:
var emailReg = /^(([^<>()[\]\\.,;:\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,}))$/igm;
Instead of using click() to submit your form, use submit():
Just change the top of your javascript code so it looks like this:
$(document).ready(function () {
$('form.contact-form').submit(function (e) {
e.preventDefault(); // <-- prevents normal submit behavior
And change your button to type=submit
<button type="submit" id="contact-submit" class="btn-contact">Submit</button>
Related
I'm not a tech completely, and I'm trying to build my custom theme for WordPress.
So, I came to a point that I need to implement a custom JS script to send the form data. As far as I understand, it's going to be a PHP file, but now I'm concentrated on front-end. This is AJAX + jQuery validation.
I don't want my form to refresh the page after it sends the data, just a simple message telling that everything went successful.
Can anyone have a look at the code I wrote and tell me what's wrong with it? It took me just two days..
PS - the file, that stores that code is embedded into WP theme properly, with a jQuery as a dependancy. I wonder, do I have to do anything to implement AJAX, or it comes with jQuery?
http://codepen.io/anon/pen/MpdRpE
<form class="form">
<div class="form__item form__item_no-margin">
<input type="text" name="firstname" placeholder="What's your name?*" class="firstname" required>
<p class="error-message">Sorry, but this field can't be empty.</p>
</div>
<div class="form__item">
<input type="text" name="email" placeholder="What's your email address?*" class="email" required>
<p class="error-message">Oopps, I haven't seen emails like that.</p>
</div>
<div class="form__item">
<textarea name="comment" placeholder="Want to leave any message?*" class="textarea" required></textarea>
<p class="error-message">Nothing to say at all? Really?</p>
</div>
<div class="form__item">
<input type="button" name="submit" value="Send" class="submit-btn">
<p class="error-message error-message_main val-error">All the required fields have to be filled out.</p>
<p class="error-message error-message_main_success val-success">Thanks. I'll contact you ASAP!</p>
</div>
</form>
.error-message {
display: none;
}
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(){
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
if(name === "" || email === "" || message === "") {
jQuery(".val-error", ".error-message").css("display", "block");
}
else {
jQuery.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:firstname, email:email, message:comment},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
First you need to prevent the default click event
Second you need a action variable to pass to the wordpress hook
3th you jquery selector for showing the errors is incorrect, the coma needs to be in the string
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(e){
e.preventDefault();
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
if(name === "" || email === "" || message === "") {
jQuery(".val-error, .error-message").show();//a little bit cleaner
}
else {
jQuery.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:firstname, email:email, message:comment,action:'validate_form'},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
for more information read the wp documentation on ajax
Little changes required otherwise code is looking fine.Have a look
$(document).ready(function(){
$(".submit-btn").click(function(){
var name = $(".firstname").val();
var email = $(".email").val();
var message = $(".textarea").val();
if(name === "" || email === "" || message === "") {
$(".val-error", ".error-message").css("display", "block");
return false;
}
else {
$.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:name, email:email, message:message},
success: function(data) {
if(data){
$("form").trigger("reset");
$(".val-success").show(fast);
}
}
});
}
});
});
I'm making a ajax call to a server side function to send an email. It works fine. My issue is before sending the email i need to validate the captcha where the server side code resides in CaptchaValidation.php. If i call "CaptchaValidation.php" on form action it should work fine but here since i'm doing a ajax call i need to use e.preventDefault();. So that form action is not working.
How can i make it work?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#divLoading').hide();
$('#appointment').submit(function (e) {
e.preventDefault();
var serviceURL = 'WebService.asmx/SendMail';
var Name = $("#fname").val();
var Email = $("#email").val();
var Telephone = $("#phone").val();
var Comment = $("#comment").val();
if ($("#fname").val().length == 0) {
alert("Please Enter Name");
$("#fname").focus();
return false;
}
if ($("#email").val().length == 0) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf("#") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf(".") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
$('#divLoading').show();
$.ajax({
type: "POST",
url: serviceURL,
data: '{"name":"' + Name + '","address":"' + Email + '","telephone":"' + Telephone + '","comment":"' + Comment + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
// alert("Mail Sent!");
$('#divLoading').hide();
window.location = "contat-submit.php";
}
function errorFunc() {
// alert('error');
}
});
});
</script>
</head>
<body>
<form name="appointment" id="appointment" method="post" action="CaptchaValidation.php">
<div>
</div><div id="leftcolumn4"><div class="h2">Contact Form</div>
<form name="appointment" id="Form1" method="post" action="send_contact.php">
Full Name:
<br />
<label>
<input name="fname" type="text" class="form-input" id="fname" size="30" />
</label>
<br /><br />
Email Address:<br />
<label>
<input name="email" type="text" class="form-input" id="email" size="30" />
</label><br /><br />
Telephone:
<br />
<label>
<input name="phone" type="text" class="form-input" id="phone" size="30" />
</label>
<br /><br />
Your Comment:<br />
<label>
<textarea name="comment" cols="28" rows="4" class="form-input-box" id="comment"></textarea><br />
<br />
</label><input name="submit" type="submit" class="form-input-submit" value="Submit" id="btnMail"/>
</div>
</form>
</body>
</html>
Follow the steps:
Change the Submit button to a simple button so that on click of that button the form will not submit.
On Click of that button call a function which will have call e.preventDefault();
function callSubmit() {
// do ajax call
}
You are doing ajax call in e.preventDefault() function. So in AJAX response, you have to check if the AJAX response is correct then do a form submit using:
$('#appointment').submit()
Now just remove the e.preventDefault(); function from you form.submit function you have written. This will allow to AJAX submit and send email.
jquery ajax form: loading image only and doesnt stop and success message not working
this is my contact form
<form method="post" action="" class="comments-form" id="contactform" />
<p class="input-block">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p class="input-block">
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p class="input-block">
<label for="message">Message:</label>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</p>
<p class="input-block">
<button class="button default" type="submit" id="submit">Submit</button>
</p>
</form>
and this is my jquery ajax function that is not working
(function() {
if($('#contactform').length) {
var $form = $('#contactform'),
$loader = '<img src="images/preloader.gif" alt="Loading..." />';
$form.append('<div class="hidden" id="contact_form_responce">');
var $response = $('#contact_form_responce');
var $p
$response.append('<p></p>');
$form.submit(function(e){
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $("#contactform").serialize()
};
//send data to server
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
if(response.is_errors){
$response.find('p').removeClass().addClass("error type-2");
$.each(response.info,function(input_name, input_label) {
$("[name="+input_name+"]").addClass("wrong-data");
$response.find('p').append('Please enter correctly "'+input_label+'"!'+ '</br>');
});
} else {
$response.find('p').removeClass().addClass('success type-2');
if(response.info == 'success'){
$response.find('p').append('Your email has been sent!');
$form.find('input:not(input[type="submit"], button), textarea, select').val('').attr( 'checked', false );
$response.delay(1500).hide(400);
}
if(response.info == 'server_fail'){
$response.find('p').append('Server failed. Send later!');
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $form.offset().top + $form.outerHeight() - $(window).height();
if($(document).scrollTop() < bottomPosition) {
$('html, body').animate({
scrollTop : bottomPosition
});
}
if(!$('#contact_form_responce').css('display') == 'block') {
$response.show(450);
}
});
e.preventDefault();
});
}
})();
and this is my contact-send.php that saves the message in my database.
require_once "../includes/database.php";
$cname=$_POST['name'];
$cemail=$_POST['email'];
$cmessage=$_POST['message'];
$date=date("Y-m-d");
$sql = "INSERT INTO messages (sendername,senderemail,message,datesent) VALUES (:name,:email,:message,:date)";
$qry = $db->prepare($sql);
$qry->execute(array(':name'=>$cname,':email'=>$cemail,':message'=>$cmessage,':date'=>$date));
I think your issue is here:
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
//--^--------------------------------------missing '$'
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
//----^------------------------------------used the '$' for other codes
try to put a $ here and see if this solves the issue:
$response = $.parseJSON(response);
and if you are getting some ajax errors plz mention it.
I am having some problems adding a reCaptcha to my jQuery AJAX form.
I have tried following the documentation, in particular this page, but had no luck.
If I use the "Challenge and Non-JavaScript API", adding the code
before the send button, I get no output.
If I try with the method
called "AJAX API" adding a custom div inside the form, I don't get
anything anyway. Basically I am not able to show and then validate
it.
This is the code that I have so far.
My form:
<div id="contactForm"><img src="img/contact-form.png" width="250" height="365" alt="contact" /></div>
Name: <span class="contactErrorFloat" id="err-name">Need the name</span>
<input name="name" id="name" type="text" placeholder="Name.." />
Email: <span class="contactErrorFloat" id="err-email">Need email</span><span class="contactErrorFloat" id="err-emailvld">Email not valid.</span>
<input name="email" id="email" type="text" placeholder="Email.." />
Message:
<textarea name="message" id="message" rows="10" placeholder="Message.."></textarea>
<button id="send">Send</button>
<div class="contactError" id="err-form">Error during validation</div>
<div class="contactError" id="err-timedout">Timeout</div>
<div class="contactError" id="err-state"></div>
<div id="ajaxsuccess">Email sent!</div>
</form>
My Script:
jQuery(document).ready(function ($) {
$('#send').click(function(){
$('.error').fadeOut('slow'); // Resetta i messaggi di errore, nascondendoli
var error = false;
var name = $('input#name').val();
if (name == "" || name == " ") {
$('#err-name').fadeIn('slow');
error = true;
}
var email_compare = /^([a-z0-9_.-]+)#([da-z.-]+).([a-z.]{2,6})$/;
var email = $('input#email').val();
if (email == "" || email == " ") {
$('#err-email').fadeIn('slow');
error = true;
} else if (!email_compare.test(email)) {
$('#err-emailvld').fadeIn('slow');
error = true;
}
if (error == true) {
$('#err-form').slideDown('slow');
return false;
}
var data_string = $('#ajax-form').serialize();
$.ajax({
type: "POST",
url: $('#ajax-form').attr('action'),
data: data_string,
timeout: 6000,
error: function(request, error) {
if (error == "timeout") {
$('#err-timedout').slideDown('slow');
} else {
$('#err-state').slideDown('slow');
$('#err-state').html('C\'è stato un errore: ' + error + '');
}
},
success: function () {
$('ajax-form').slideUp('slow');
$('#ajaxsuccess').slideDown('slow');
}
});
return false;
});
});
There is also a PHP file with the php function to send the email but I don't think it's much important actually. I would really LOVE if someone could give me any help to implement this. Thanks a lot!
first of all you have to sign in to recaptcha. You can do this here:
recaptcha.net
then you can get your key. Then you embed the key into the sample code.
Here
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/challenge?k=**your_public_key**">
and here
<iframe src="http://www.google.com/recaptcha/api/noscript?k=**your_public_key**"
height="300" width="500" frameborder="0"></iframe>
The contact form it´s working, if you fill it all it sends the message. The problem if you don´t fill in the email box, the form doesn´t alert you about it, is there anyway that I can show a word or somekind of alert to the user?
this is my markup:
<div class="form">
<h2>ESCRIBENOS</h2>
<form method="post" action="process.php">
<div class="element">
<label>Nombre (obligatorio):</label><br/>
<input type="text" name="name" class="text" />
</div>
<div class="element">
<label>Email (obligatorio):</label><br/>
<input type="text" name="email" class="text" />
</div>
<div class="element">
<label>Telefono:</label><br/>
<input type="text" name="website" class="text" />
</div>
<div class="element">
<label>Mensaje:</label><br/>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
</div>
And this is my script:
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&website=' +
website.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "../process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
Can someone help me out please?
Try this:
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
$('input[type=text]').each(function(){
if($(this).val().length == 0){
$(this).addClass('hightlight');
alert('Empty input field')
return false;
}
});
.... rest of your code
Note: This does not work for textarea but I think you can figure that out yourself!
EDIT:
var valid = false;
$('input[type=text]').each(function(){
if($(this).val().length == 0){
$(this).addClass('hightlight');
alert('Empty input field')
valid = false;
}else{
valid = true;
}
});
if(valid == false) return;
console.log('All input fields are filled in..');
... rest of your code. You can remove al the if else statements for input fields. For checking the textarea you could give all fields the same class and do:
$('form.classofallelements').each(function(){