reCAPTCHA using ajax, PHP and Jquery – how to implement it

reCAPTCHA using ajax, PHP and Jquery!

First of all you need to get access to recaptcha. So click HERE and look at the right up corner – there is a button saying Get “reCAPTCHA” – click on it and login into your google account, if needed. In the form at the same page fill your group label and add the domains that you will use the reCAPTCHA on – if you don’t have a domain, don’t worry – reCAPTCHA is working by default on localhost.

recaptcha using ajax
recaptcha using ajax

Once the website is added, you will see a table right above the form containig the name and the URL – click on it.

There you will see this:

recaptchaKeys

  • Click on Step 1 and copy-paste the first snippet(script) before the closing </head> tag on your HTML template.
  • Copy the second snippet(div) and paste it where you want the widget to appear.

If you save your file and refresh you will see that reCAPTCHA is shown on the page. What we need is to verify the user input.

In order to do this we have to create an ajax request to our server and verify if everything is ok.

Here is a simple javascript that will do the job:

[code language=”javascript”]
$("#butoonID").click(function () {
/* Check if the captcha is complete */
if ($("#g-recaptcha-response").val()) {
$.ajax({
type: ‘POST’,
url: "verify.php", // The file we’re making the request to
dataType: ‘html’,
async: true,
data: {
captchaResponse: $("#g-recaptcha-response").val() // The generated response from the widget sent as a POST parameter
},
success: function (data) {
alert("everything looks ok");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("You’re a bot");
}
});
} else {
alert("Please fill the captcha!");
}
});
[/code]

Ok the above code will send a request to our verify.php file and we need to handle this request and check if the captcha is not abused.

verify.php

[code language=”php”]
$captcha = filter_input(INPUT_POST, ‘captchaResponse’); // get the captchaResponse parameter sent from our ajax

/* Check if captcha is filled */
if (!$captcha) {
http_response_code(401); // Return error code if there is no captcha
}
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR-SECRET-KEY-HERE&amp;amp;response=" . $captcha);
if ($response . success == false) {
echo ‘SPAM’;
http_response_code(401); // It’s SPAM! RETURN SOME KIND OF ERROR
} else {
// Everything is ok and you can proceed by executing your login, signup, update etc scripts
}
[/code]

What just happened in this reCAPTCHA  using ajax implementation tutorial?

First of all take a look at the $response variable – we are constructing a link there and this link contains your private key. Now take a look at the last screenshot above – you can get this key by clicking on Step 2 – server side integration

We got the “captchaResponse” which was send via ajax to our PHP back end script. We made 2 checks – the first checks if the captcha response is not empty(just in case) – if it’s empty, then we do nothing. We also check if the response is true, or false. If it’s false it means that we are probably dealing with a bot or a spammer.

If you did everything as described in the tutorial you have a working reCAPTCHA  using ajax and php!

You also can also easily implement it in this simple PHP ajax signup form.

8 thoughts on “reCAPTCHA using ajax, PHP and Jquery – how to implement it”

  1. This is exactly what I was looking for! All the other AJAX tutorials were for the old reCaptcha api v1. I struggled with integrating reCaptcha with our AJAX contact form for longer than I care to admit before finding your post. Thanks!

      1. Thank you very much for your answer.
        I follow this tutorial step by step. Here is my sourcecode:

        My Index-Document:

        Some Title

        $(“#form1”).click(function () {
        /* Check if the captcha is complete */
        if ($(“#g-recaptcha-response”).val()) {
        $.ajax({
        type: ‘POST’,
        url: “verify.php”, // The file we’re making the request to
        dataType: ‘html’,
        async: true,
        data: {
        captchaResponse: $(“#g-recaptcha-response”).val() // The generated response from the widget sent as a POST parameter
        },
        success: function (data) {
        alert(“everything looks ok”);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(“You’re a bot”);
        }
        });
        } else {
        alert(“Please fill the captcha!”);
        }
        });

        Processing an AJAX Form

        Submit

        _________________________________________________________
        verify.php :
        $captcha = filter_input(INPUT_POST, ‘captchaResponse’); // get the captchaResponse parameter sent from our ajax

        /* Check if captcha is filled */
        if (!$captcha) {
        http_response_code(401); // Return error code if there is no captcha
        }
        $response = file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret=###SECRET-KEY-PLACEHOLDER###&response=” . $captcha);
        if ($response . success == false) {
        echo ‘SPAM’;
        http_response_code(401); // It’s SPAM! RETURN SOME KIND OF ERROR
        } else {
        // Everything is ok and you can proceed by executing your login, signup, update etc scripts
        }
        __________________________________________________________

        After the recaptcha validating i get this error message:
        Notice: Use of undefined constant success – assumed ‘success’ in C:xampphtdocsentwicklungtestajax_versiong_testverify.php on line 9

  2. but is this way is safe ? ? any one can change the condition of receiving data in the JavaScript code
    and that what it can be happen

Leave a Comment

Your email address will not be published. Required fields are marked *