How to validate google recaptcha on client side?

21,182

I share my code solution. But the proxy.php and other details with the full explanation (incl. backend part) you might find here.

Recaptcha with data-callback parameter

<script src="https://www.google.com/recaptcha/api.js" >;
<form method="post">
<div class="g-recaptcha" data-sitekey="[site_key]" data-callback="onReturnCallback" data-theme="light"></div>
<input value="submit" type="submit" />
</form>

JS validation

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var onReturnCallback = function(response) { 
    //alert('g-recaptcha-response: ' + grecaptcha.getResponse()); 
    var url='proxy.php?url=' + 'https://www.google.com/recaptcha/api/siteverify';  
    $.ajax({ 'url' : url, 
               dataType: 'json',
               data: { response: response},
               success: function( data  ) {                     
                var res = data.success.toString();
                        alert( "User verified: " + res);                    
                if (res ==  'true') { 
                       document.getElementById('g-recaptcha').innerHTML = 'THE CAPTCHA WAS SUCCESSFULLY SOLVED'; 
                                } 
                           } // end of success: 
         }); // end of $.ajax 
}; // end of onReturnCallback 
</script>

Note!

The backend part, proxy.php, is necessary because of security issue.

Share:
21,182
Gaurav_0093
Author by

Gaurav_0093

Updated on July 01, 2020

Comments

  • Gaurav_0093
    Gaurav_0093 almost 4 years

    I have implemented google reCaptcha on a login panel showing after 3 unsuccessful login

    But I want to validate reCaptcha on a client slide using jQuery on clicking of login button here is the code

    <div style="display:none;width:310px;top:205px;left:558px;position:absolute" id="grecaptcha" runat="server">
      <cc1:GoogleReCaptcha  ID="ctrlGoogleReCaptcha1"  runat="server" PublicKey="6LdHrQ0TAAAAAD77ubv9Jr6q4RYkyddhXzX-XPB3" PrivateKey="xxxxxxx" />
    
      </div>
      <span id="captcha" style="margin-left:588px;color:red" />
    <asp:Button ID="LoginButton" runat="server" OnClientClick="get_action();" CommandName="Login" Text="Inloggen" ValidationGroup="Login1" />
    

    How can I do this by using jQuery?