Home Ask Login Register

Developers Planet

Your answer is one click away!

Reza February 2016

Load reCAPTCHA dynamically

There are several ways to load reCAPTCHA using javascript such as below:

<html>
  <head>
    <title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script type='text/javascript'>
    var captchaContainer = null;
    var loadCaptcha = function() {
      captchaContainer = grecaptcha.render('captcha_container', {
        'sitekey' : 'Your sitekey',
        'callback' : function(response) {
          console.log(response);
        }
      });
    };
    </script>
  </head>
  <body>
      <div id="captcha_container"></div>
      <input type="button" id="MYBTN" value="MYBTN">
      <script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
  </body>
</html>

This code load captcha on pageload. I want load reCAPTCHA just when clicked on "MYBTN". So the code changes into:

<html>
  <head>
    <title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script type='text/javascript'>
$('#MYBTN').on('click',function(){
    var captchaContainer = null;
    var loadCaptcha = function() {
      captchaContainer = grecaptcha.render('captcha_container', {
        'sitekey' : 'Your sitekey',
        'callback' : function(response) {
          console.log(response);
        }
      });
    };
 });
    </script>
  </head>
  <body>
      <div id="captcha_container"></div>
      <input type="button" id="MYBTN" value="MYBTN">
      <script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
  </body>
</html>

But this code didn't work when I click on "MYBTN" and reCAPTCHA not load. Help

Answers


Gavriel February 2016

You just need to call loadCaptcha()

$('#MYBTN').on('click',function(){
    var captchaContainer = null;
    var loadCaptcha = function() {
      captchaContainer = grecaptcha.render('captcha_container', {
        'sitekey' : 'Your sitekey',
        'callback' : function(response) {
          console.log(response);
        }
      });
    };
    loadCaptcha(); // THIS LINE WAS MISSING
 });
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
      <div id="captcha_container"></div>
      <input type="button" id="MYBTN" value="MYBTN">
      <script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit"></script>

Post Status

Asked in February 2016
Viewed 3,992 times
Voted 4
Answered 1 times

Search




Leave an answer


Quote of the day: live life