Google reCAPTCHA with AJAX, grecaptcha.render() error: grecaptcha is not defined


I faced with a strange error message when implemented a Google reCAPTCHA Version 2.0 based web site protection using AJAX.


There is a sample form containing a DIV with the id = "g-recaptcha" to display reCAPTCHA widget:

<form method="post">
...
<div id="g-recaptcha"></div>
...
</form>

After loading form by jQuery's ajax, I tried to render and display the reCAPTCHA widget by calling grecaptcha.render() API function.

$(document).ready(function () {
    $.ajax({
        url: 'my-sample-form.html'
    }).done(function (data) {
        $("#form-box").html(data);
        grecaptcha.render('g-recaptcha', {
            'sitekey' : 'my-site-key'
        });
    }).fail(function (jqXHR, textStatus, errorThrown) {
        ...
    });
});

It failed with the error message: grecaptcha is not defined


The workaround to get it work:

1. Specified callback function in Javascript resource as given in Google reCAPTCHA documentation

<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaOnload&render=explicit" async defer></script>


2. The rest of the code is self-explanatory )

var recaptchaScriptLoaded = false;
var recaptchaAjaxReady = false;

function recaptchaOnload()
{
    recaptchaScriptLoaded = true;
    recaptchaRender();
}

function recaptchaRender() {
    if (recaptchaScriptLoaded && recaptchaAjaxReady)
    {
        grecaptcha.render('g-recaptcha', {
            'sitekey' : 'my-site-key'
        });
    }
}

$(document).ready(function () {
    $.ajax({
        url: 'my-sample-form.html'
    }).done(function (data) {
        $("#form-box").html(data);
            recaptchaAjaxReady = true;
            recaptchaRender();
    }).fail(function (jqXHR, textStatus, errorThrown) {
        ...
    });
});

Google reCAPTCHA

Hope this helps.



IT / Coding / How-To


Other Topics