Magento – Magento 1.9 : Validate the Google reCaptcha in custom popup

captchamagento-1.9recaptcha

I have added the google recaptcha in custom popup. But, form is also submitting without captcha.

I have used following codes for captcha:

 <script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="XXXXXXXXXX"></div>

I have also used js code for validating. But, I think it's not proper way to validate it.

=> js code :

function checkcaptcha() {
        if((jQuery('#g-recaptcha-response').val())=='') {
            jQuery('.captcha-error').css('display','block');
            return false;
        } else {
            jQuery('.captcha-error').css('display','none');
        }

    }

Please help me for validating reCaptcha in proper way.

Thanks.

Note : Do not suggest any extension link here. I want to check programmatically.

Best Answer

I think you have to try with using google recaptcha div class instead of id in jquery to getting google recaptcha response. I have tried below code and it's working for me:-

<div class="news-captcha">
  <div class="g-recaptcha" data-sitekey="XXXXXXXXXX"></div>
</div>

JS CODE:-

var googleResponse = jQuery('.news-captcha .g-recaptcha-response').val();
if (googleResponse!= ""){
    return true;
}
else {
    return false;
}

After getting response you have to pass this response in input "hidden" field. In the form submit action controller function you can use this hidden field post value and check there that recaptcha response getting or empty response.

Related Topic