最佳答案
I'm use reCaptcha v2 but in dev console response Uncaught (in promise) null
in in any case (and moving the .reset()
function)
console:
my code for recaptcha:
<div class="text-xs-center" style="text-align: center; height:150px;">
<p style="color: black;"> Complete the verification: </p>
<div style="display: inline-block;" class="g-recaptcha" data-sitekey="xxxxxxxxxxx" data-callback="callback"></div>
</div>
my callback function:
function callback() {
if (grecaptcha === undefined) {
alert('Recaptcha non definito');
return;
}
var response = grecaptcha.getResponse();
console.log(response);
if (!response) {
alert('Coud not get recaptcha response');
return;
}
$.ajax({
'url' : 'validate-recaptcha.php',
'type' : 'POST',
'data' : {
'response' : response
},
'success' : function(data) {
alert('Data: '+data);
},
'error' : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
grecaptcha.reset();
}
and my validate-recaptcha.php:
<?php
//debug
$fp = fopen('debug.txt', 'a');
fwrite($fp, print_r($_POST, TRUE));
fclose($fp);
//enddebug
if (empty($_POST['recaptcha'])) {
exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(
array (
'response' => $response,
'secret' => 'yoursecretkey',
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$opts = array('http' =>
array (
'method' => 'POST',
'header' => 'application/x-www-form-urlencoded',
'content' => $post
)
);
$context = stream_context_create($opts);
$serverResponse = @file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if (!$serverResponse) {
exit('Failed to validate Recaptcha');
}
$result = json_decode($serverResponse);
if (!$result -> success) {
exit('Invalid Recaptcha');
}
exit('Recaptcha Validated');
Searching on the internet, probably the problem is the .reset()
function, but I do not understand the solution.