naeemqaswar
11/14/2016 - 10:24 AM

Google captcha recaptcha

Google captcha recaptcha

<html>
    <head>
        <title>Loading captcha with JavaScript</title>
    </head>
    <body>

        <form action="" method="POST">
            <label>Username: <input type="text" name="username" /></label>
            <small>Are you a robot?</small>
            <div id="captcha_container"></div>
            <input type="submit" value="Submit">
        </form>

        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
        <script type='text/javascript'>
            var captchaContainer = null;
            var loadCaptcha = function() {
                captchaContainer = grecaptcha.render('captcha_container', {
                    'sitekey' : '6LcoeCkTAAAAAPATFmgjUkDSMYVmwBFw7PzQ-5DM',
                    'callback' : function(response) {
                    }
                });
            };
            $('form').on('submit', function (e) {
                e.preventDefault();
                var response = grecaptcha.getResponse();
                //recaptcha failed validation
                if(response.length == 0) {
                    e.preventDefault();
                    alert('no captcha selected');
                }
                else {
                    alert('form submitted');
                }
            });
        </script>
    </body>
</html>