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?
JavaScript
x
4
1
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
2
3
<div class="g-recaptcha" data-sitekey="6Lf-wAIaAAAAALa36iP4tIvwCeub0-bAB3QfqWbP"></div>
4
best I found is here – https://developers.google.com/recaptcha/docs/verify
and tried this:
JavaScript
1
5
1
$('#btn').on('click', function(){
2
let rc = grecaptcha.getResponse();
3
console.log(rc.success); // undefined
4
});
5
any help
Advertisement
Answer
Here you have a working example in Php
JavaScript
1
22
22
1
define('SITE_KEY','SDFSDF4UAAAAAM-ISDM2lM5WESDVSDCERGDFGSDFG');
2
define('SECRET_KEY','SGSFGFDSAACJ_OxaXzSayvQS_ABCDECSDFSDF');
3
4
5
if ($_POST) {
6
function getcaptcha($secretkey){
7
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?
8
secret=".SECRET_KEY."&response={$secretkey}");
9
$respuesta = json_decode($response);
10
return $respuesta;
11
}
12
13
$return = getcaptcha($_POST['g-recaptcha-response']);
14
var_dump($return);
15
if ($return->success == true && $return->score >0.5) {
16
echo "You are a Person...";
17
}
18
else{
19
echo "You are a robot... ";
20
}
21
}
22
and the Javascript
JavaScript
1
10
10
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8">
5
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6
<title>Recaptcha V3 by AleDC</title>
7
8
9
<script src="https://www.google.com/recaptcha/api.js?render=<?php echo SITE_KEY; ?>"></script>
10
JavaScript
1
20
20
1
<form action="index.php" method="post">
2
3
Nombre: <input type="text"> <br>
4
TOKEN: <input type="text" name="g-recaptcha-response" id="g-recaptcha-response"><br>
5
<input type="submit" value="submit">
6
7
8
9
</form>
10
11
<script>
12
grecaptcha.ready(function() {
13
grecaptcha.execute('<?php echo SITE_KEY; ?>', {action: 'homepage'})
14
.then(function(token) {
15
console.log(token);
16
document.getElementById("g-recaptcha-response").value=token;
17
});
18
});
19
</script>
20
Remember that you must register your website in the google recaptcha portal