Securing AJAX calls with reCaptcha

reCAPTCHA is one of the most popular solutions when it comes to securing forms on websites. You may like it or not, but it is widespread and well-known to the users too. The typical use case is to put it as one of the form fields and validate it server-side once the form is sent. This means that we can also use the same behavior to secure AJAX calls and perform certain actions only if the captcha is filled properly.

The below example is based on reCAPTCHA v2, which is the most common one at the moment of preparing this post. The same principle will be valid for reCAPTCHA v3.

In the typical use case, the captcha is placed somewhere on the page, using JavaScript and div element that is filled by the script:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="g-recaptcha" data-sitekey="#reCaptchaSiteKey#"></div>

When performing an AJAX call, results of the captcha validation can be simply pulled and sent with the AJAX call data. Below is the sample code, using good old jQuery 🙂 – the key element is to pull the value of the form field named “g-recaptcha-response”:

function performAJAX() {
    let captcha = $('[name=g-recaptcha-response]');
    $.ajax({
         url: 'ajaxHandler.html',
         data: {
            captcha: (captcha.length?captcha[0].value:''),
            // other data fields
         },
    });
}

Server-side, you can now validate captcha response as you do with regular forms. Once the response is valid, the AJAX call can be processed. Otherwise, an error message should be displayed.