I have an input and a google recaptcha
and need to send input value only if the captcha is solved
after page reload the value of grecaptcha.getResponse()
is an empty string
when captcha is resolved by a single click – the value is a long string – differ after each page load
how to know what is the value if the captcha says – you're a robot
or something like that
in other words how to cancel sending data if captcha is not solved successfully?
<script src="https://www.google.com/recaptcha/api.js" async defer></script> <div class="g-recaptcha" data-sitekey="6Lf-wAIaAAAAALa36iP4tIvwCeub0-bAB3QfqWbP"></div>
best I found is here – https://developers.google.com/recaptcha/docs/verify
and tried this:
$('#btn').on('click', function(){ let rc = grecaptcha.getResponse(); console.log(rc.success); // undefined });
any help
Advertisement
Answer
Here you have a working example in Php
define('SITE_KEY','SDFSDF4UAAAAAM-ISDM2lM5WESDVSDCERGDFGSDFG'); define('SECRET_KEY','SGSFGFDSAACJ_OxaXzSayvQS_ABCDECSDFSDF'); if ($_POST) { function getcaptcha($secretkey){ $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify? secret=".SECRET_KEY."&response={$secretkey}"); $respuesta = json_decode($response); return $respuesta; } $return = getcaptcha($_POST['g-recaptcha-response']); var_dump($return); if ($return->success == true && $return->score >0.5) { echo "You are a Person..."; } else{ echo "You are a robot... "; } }
and the Javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Recaptcha V3 by AleDC</title> <script src="https://www.google.com/recaptcha/api.js?render=<?php echo SITE_KEY; ?>"></script>
<form action="index.php" method="post"> Nombre: <input type="text"> <br> TOKEN: <input type="text" name="g-recaptcha-response" id="g-recaptcha-response"><br> <input type="submit" value="submit"> </form> <script> grecaptcha.ready(function() { grecaptcha.execute('<?php echo SITE_KEY; ?>', {action: 'homepage'}) .then(function(token) { console.log(token); document.getElementById("g-recaptcha-response").value=token; }); }); </script>
Remember that you must register your website in the google recaptcha portal