M. Liuha M. Liuha - 22 days ago 4
HTML Question

How to integrate reCaptcha v2 with JS & PHP form?

So, I have used a contact form that uses HTML, JS and PHP to send me an email. I would like to add reCaptcha, but haven't figured out yet how to do that. Can someone help me, please? :)

The snippet contains JS & HTML, PHP is in under that.



// Contact Form Scripts

$(function() {

$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message,
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');

//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
});
},
filter: function() {
return $(this).is(":visible");
},
});

$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});

<form name="sentMessage" id="contactForm" novalidate>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-center">
<div id="success"></div>
<button type="submit" class="btn btn-xl">Send Message</button>
</div>
<div class="g-recaptcha" data-sitekey="6LfFrQgUAAAAAGZSQvSfEqXKgvoGObpwE_rreeur"></div>

</div>
</form>





PHP:

<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||

!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))

{
echo "No arguments Provided!";
return false;
}

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to = 'email@email.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Answer

To resolved Uncaught ReferenceError: $ is not defined, add <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jque‌​ry.min.js"> before your JS file inclusion.

This should solve Uncaught ReferenceError: $ is not defined issue.

EDIT: As you done everything related to your form. Now first step is Get reCAPTCHA API keys. For adding reCAPTCHA to your site, you need to register your site and get reCAPTCHA API keys.

You can register your site at Google from here and get your Site Key which is used to display the reCAPTCHA widget. Here you also get Secret key which helps to authorizes communication between your site and the reCAPTCHA server.

The second step is reCAPTCHA API javaScript library inclusion. Use below code to include this reCAPTCHA API JS library.

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Then third step is use widget into your form. You need to place a simple Google reCAPTCHA widget <div> at before the Submit button. Replace YOURSITEKEY at the data-sitekey attribute value with your Site Key from first step.

<div class="g-recaptcha" data-sitekey="YOURSITEKEY"></div>

The final and forth step is handle the Google reCAPTCHA API authorization reponse with your server side code to validation your form with Google reCAPTCHA. Just replace YOURESECRETKEY with your actual secret code from step first.

$errMsg = '';
if(isset($_POST['submit']) && !empty($_POST['submit'])):
        //Check google recaptcha reponse...
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
        //your site secret key
        $secret = 'YOURESECRETKEY';
        //get verify response data
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);
        if($responseData->success):
            //Success: do code to store your data...
        else:
            $errMsg = 'Robot verification failed, please try again.';
        endif;
    else:
        $errMsg = 'Please click on the reCAPTCHA box.';
    endif;

    //If any error...
    if(!empty($errMsg)) :
        print $errMsg;
        return false;
    endif;
endif;