Adding reCaptcha to this jQuery AJAX form - php

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>

Related

Ajax and jQuery custom form submission in Wordpress

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);
}
}
});
}
});
});

jQuery Ajax form not submitting on iPhone

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>

Form when submitted to display a result (Firstname) on the thank you page

Stuck on a thing with PHP, i know it is something simple but am not sure of the correct way of doing it, either by jquery or php.
I have a contact form which when it submits its form, i want the results of some of the fields to display on the results thank you paeg saying:
Thank you for entering YOURNAME. Blah blah blah
Is this acheivable with a simple line of php or does it need to called through jquery.
Thanks, only new to php so somethings are still bit confusing
<?php
define('is_freetrial-celebrity', 1);
include_once('includes/header.inc.php');
?>
<div role="main" id="main">
<article id="mainFreetrial" class="greyBlock twoColumnsLayout">
<header>
<h1>Get Started</h1>
</header>
<div>
<form method="get" action="/forms_validation/freetrial.php" class="trialForm ajaxForm">
<div class="column">
<p>
<label for="firstNameTrial">First name<sup class="red">*</sup></label><input type="text" id="firstNameTrial" name="firstNameTrial" value="" required/>
</p>
<p>
<label for="lastNameTrial">Last name<sup class="red">*</sup></label><input type="text" id="lastNameTrial" name="lastNameTrial" value="" required/>
</p>
<p>
<label for="ageTrial">Age</label><input type="text" id="ageTrial" name="ageTrial" value=""/>
</p>
<p>
<label for="celebrityTrial" style="display: block; width: auto; margin-bottom: 5px;">Name the celebrity you would most like to meet, and why?<sup class="red">*</sup></label>
<textarea id="celebrityTrial" name="celebrityWhyTrial" style="width: 430px; height: 3em;" required></textarea>
</p>
<p class="ajaxFormBeforeValid">
<input type="submit" value="Submit now" class="redButton"/><span class="ajaxFormWait"></span><span class="ajaxFormError error"></span>
</p>
<div class="ajaxFormValid">
<p>
Thank you! Your local consultant will contact you soon. 'Like' us while you wait for all the latest VIP offers and promotions!
</p>
</div>
<p>
<small>
<sup class="red">*</sup>These are mandatory fields.
</small>
</p>
</div>
</form>
</div>
</article>
</div>
<?php include_once('includes/footer.inc.php'); ?>
Heres the jquery part
/*************************
plugin to manage ajax forms
*************************/
(function( $ ){
var methods = {
init : function( options ) {
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm'),
ajaxForm = $('<div />', {
text : $this.attr('title')
});
// If the plugin hasn't been initialized yet
if ( ! data ) {
$(this).data('ajaxForm', {
target : $this,
ajaxForm : ajaxForm
});
//get the spinner, the valid box and the error box
var mySpinner = $this.find('.ajaxFormWait');
var myValid = $this.find('.ajaxFormValid');
var myError = $this.find('.ajaxFormError');
var myBeforeValid = $this.find('.ajaxFormBeforeValid');
myError.hide();
mySpinner.hide();
//add an event to send the form via AJAX
$this.submit(function(){
// get all the inputs into an array.
var $inputs = $this.find(':input:not([type="submit"], [type="button"])');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
if (this.type == "radio" || this.type == "checkbox"){
if($(this).is(':checked')){
if(typeof(values[this.name]) === 'undefined'){
values[this.name] = $(this).val();
}else{
values[this.name] += ', '+($(this).val());
}
}
} else
values[this.name] = $(this).val();
});
function defineTheInvalidsFields(fieldsList){
for(var i in fieldsList){
if(fieldsList[i] == 'closestStudio'){
$this.find('[name="'+fieldsList[i]+'"]').parent().addClass('invalid');
}else{
$this.find('[name="'+fieldsList[i]+'"]').addClass('invalid');
}
}
}
//send an AJAX request
$.ajax({
url: $this.attr('action'),
dataType: 'json',
data: values,
beforeSend: function(){
mySpinner.show();
},
success: function(result){
mySpinner.hide();
$this.find('.invalid').removeClass('invalid');
//error management
if(typeof(result.valid) === 'undefined'){
if(result.multipleSend){ //if multiple send
myError.html('Your request is already sent.');
}else if(result.required){ //if fields are required
defineTheInvalidsFields(result.required);
myError.html('The fields in red are required.');
}else if(result.format){ //if the forma is incorrect
defineTheInvalidsFields(result.format);
myError.html('The fields in red have invalid content.');
}else if(result.loginInvalid){
myError.html(result.loginInvalid);
}else{
myError.html('An unknown error occured.');
}
myValid.slideUp(300);
myError.slideDown(300);
}else if(typeof(result.loginUrl) !== 'undefined'){
window.location.href = result.loginUrl;
}else{
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
}
}
});
return false;
});
//special case for the heardAbout
$('#heardAbout').change(function(){
if($(this).find('option:selected').attr('value') == 'Other'){
$('#otherHeardAbout').slideDown(300);
}else{
$('#otherHeardAbout').slideUp(300);
}
});
}
});
},
destroy : function(){
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm');
// Namespacing FTW
$(window).unbind('.ajaxForm');
data.ajaxForm.remove();
$this.removeData('ajaxForm');
})
}
};
$.fn.ajaxForm = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.ajaxForm' );
}
};
})( jQuery );
The form gets sent to the other page, is there a way to target a specific div and add the custom message with the name.
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
if You wand to fetch specific element div via ajax call You can do like this:
$.ajax({
url: 'page.html',
success: function(data) {
item=$(data).filter('#specific_element');
$(selector).html(item);
}
});
If You wand to redirect to other page using
window.location = '/free-trial-thank-you/';
and then show data on a different page You should pass needet parameters like
window.location = '/free-trial-thank-you/page.php?name1=Daniel&name2=Pablo;
and on different site show parameters using _GET or _POST for example:
echo $_GET['name1'] or echo $_POST['name1'] if You use PSOT method in Your Ajax request
One way that I can think of is using session to store the information.
At freetrial.php store the form information in session like this:
session_start();
$_SESSION['firtNameTrial'] = $_GET['firstNameTrial'];
On ajax success, redirect the page to the thank you page using javascript windows.location.replace:
// similar behavior as an HTTP redirect
window.location.replace("http://yourwebpageaddress.com/thankyou.php");
Get the session on the thank you page. If you don't know, you may look at this example: Click here for session example

Required alert on wordpress form

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(){

can not call any other function, then die my code

I'm building a login with ajax and php. My code works great until I do a call in my php code to another class. when dying my php code I get int even put a var_dump. you can see in my php code I've commented it out as I want to do really
View:
<body>
<p> </p>
<div id="content">
<h1>Login Form</h1>
<form id="form1" name="form1" action="stack.php" method="post">
<p>
<label for="username">Username: </label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="password">Password: </label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" id="login" name="login" value="submit"/>
</p>
</form>
<div id="message"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#login").click(function(){
var action = $("#form1").attr('action');
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: 'POST',
url: action,
data: form_data,
success: function(data){
if(typeof(data) != 'undefined' && (data == 'success' || data == 'error')){
if(data == 'success'){
$("#form1").slideUp('slow', function() {
$("#message").html("<p class='success'>You have logged in
successfully!</p>");
});
} else if(data == 'error'){
$("#form1").slideUp('slow', function() {
$("#message").html("<p class='error'>Invalid username and/or
password.</p>");
});
}
} else {
console.log("här");
console.log(data);
$("#message").html("<p class='error'>Error to connect to server</p>");
}
}
});
return false;
});
});
</script>
</body>
</html>
PHP:
class DologinHandler{
public function Login(){
if(isset($_REQUEST['is_ajax']))
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
// $UserHandler = new UserHandler();
//$UserHandler -> controllDB($username,$password);
if($username == 'demo' && $password == 'demo')
{
exit('success');
} else {
exit('error');
}
}
}
}
?>
If the code in your post is all the PHP code you have written, it is not going to do anything. If your client expects 'success' or 'error', the fact that it's getting an empty string may be the reason why you're getting your error message.
In PHP, when you declare a Class, the code is only executed when you instantiate that class. You can do that by adding the two lines of code Waygood wrote in his answer, to the bottom of your stack.php file.
<?php
/* All your PHP code */
$loginclass=new DologinHandler();
$loginclass->Login();
And, for good practice, if there's no content appended to the code written above, get rid of the ?> at the bottom, that can save you quite some trouble. Not related to this issue though.
try
echo 'success';
return true;
instead of
exit('success');
also at the end of the function you should deal with non-ajax login
stack.php should be something like:-
$loginclass=new DologinHandler();
$loginclass->Login();

Categories