Reputation: 125
I'm trying to implement a ReCaptcha with AJAX to verify it so that I can stop the page from submitting if the ReCaptcha fails.
Here's my JavaScript:
function verify_recaptcha(){
jQuery.post(
'verify_recaptcha.php',
{
recaptcha_challenge_field: jQuery('#recaptcha_challenge_field').val(),
recaptcha_response_field: jQuery('#recaptcha_response_field').val()
},
function(data){
if(data == "true"){
alert("ReCaptcha Verified");
}
else{
alert(data);
}
}
);
}
And the contents of verify_recaptcha.php
<?php
require_once('recaptchalib.php');
$privatekey = "-- my private key --";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
echo "false";
} else {
echo "true";
}
?>
The problem is that my test Alert is showing "true" if the recaptcha verifies (and false if it doesn't), which I don't think should be possible. It should evaluate data == "true" in that if statement and display "ReCaptcha Verified".
Most anything I search on the subject the problem is that people are trying to return a value out of the AJAX call, which I know I can't do and am not doing here.
What am I missing?
Upvotes: 0
Views: 915
Reputation: 8960
Reframed your code a bit. Try,
PHP:
...
...
$json = array();
if (!$resp->is_valid)
$json['result'] = true;
else
$json['result'] = false;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
JS:
...
...
jQuery.post(
'verify_recaptcha.php',
{
recaptcha_challenge_field: jQuery('#recaptcha_challenge_field').val(),
recaptcha_response_field: jQuery('#recaptcha_response_field').val()
})
.done(function(response){
console.log(response);
if(response.result == true)
{
// Entered captcha is correct
}
else
{
// Entered captcha is incorrect
}
});
Explanation:
1) Always return boolean true/false
and not in form of string.
2) Use .done()
. Won't make much difference from your code, but .done()
make your ajax call code much clear.
3) Always open your console
and try printing objects and see the output if it is what you are expecting.
Upvotes: 1