Google Recaptcha with AJAX

Asked

Viewed 927 times

1

I’m trying to make a form with the validation of the Google recaptcha.

What happens is that if not validating the recaptcha gives the error message asking to "check" the recaptcha but if I check the recaptcha it gives the same error asking the user to check the recaptcha

Form:

<script src='https://www.google.com/recaptcha/api.js?hl=en'></script>

<form name="sentMessage" id="contactForm" novalidate>
                    <div class="text-center">
                          <h2 class="section-heading">Get In Touch</h2>
                    </div>
                    <div class="col-md-12">
                        <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>
                        <div class="col-md-6">
                            <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>
                        <div class="col-md-4">
                             <div class="form-group">
                                <input type="tel" class="form-control" placeholder="Your Phone" id="phone">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="Your Company" id="company">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="Your Country" id="country">
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="col-md-8">
                            <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-md-12 text-right">
                            <div id="success"></div>

                            <div class="g-recaptcha col-md-4 nopadding" data-sitekey="6LeWfSATAAAAAJXNf_Ys78pY9FwXThC6t5JBqt0L"></div>
                            <button type="submit" class="btn btn-xl">Send Message</button>
                        </div>
                    </div>
                </form>

AJAX:

 $("#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 company = $("input#company").val();
        var country = $("input#country").val();
        var message = $("textarea#message").val();
         $.ajax({
            url: "../mail/form-handler.php",
            type: "POST",
            data: {
                name: name,
                phone: phone,
                email: email,
                company: company,
                country: country,
                message: message
            },
            cache: false,
            success: function(data) {
                if (data === "true") {
                     // Success message
                    $('#success').html("<div class='alert alert-success text-left'>");
                    $('#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. Thank you for contacting us. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                } else {
                     // Fail message
                    jQuery('#success').html("<div class='alert alert-danger'>");
                    jQuery('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
                    jQuery('#success > .alert-danger').append("<strong>You can't proceed ! Please mark the recaptcha to confirm you are human.");
                    jQuery('#success > .alert-danger').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, it seems that 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");
    },
});

PHP

<?php
 // busca a biblioteca recaptcha
require_once "../helpers/recaptchalib.php";
// sua chave secreta
$secret = 'SECRET KEY';

// resposta vazia
$response = null;

// verifique a chave secreta
$reCaptcha = new ReCaptcha($secret);

// se submetido, verifique a resposta
if ($_POST["g-recaptcha-response"]) {
  $response = $reCaptcha->verifyResponse(
    $_SERVER["REMOTE_ADDR"],
    $_POST["g-recaptcha-response"]
);

 }

 if ($response != null && $response->success) {
echo "true";
} else {
echo "false";
$errors[] = "Captcha mutch be filled.";
}

1 answer

1

You can reset captcha via Javascript.

grecaptcha.reset();

Include the function grecaptcha.reset(); below the $('#contactForm').trigger("reset"); for example. This will cause Captcha to be "deleted" and requires the user to fill in again.

This works only on the new Recaptcha!

The mentioned error occurs because one cannot use the same captcha to be validated again.

Another less troublesome solution for users is to define via SESSION that the user has already used that captcha and that it is correct. Worry about restricting SESSION by IP, User Agent and also by the own value of $_POST["g-recaptcha-response"] and define a short life time. If you do not take this care the Catpcha will be useless.

You can also join both solutions. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.