I'm implementing reCaptcha, and I'm using an Ajax call to a PHP page of mine to check the validity of the captcha, without a page refresh.
I have this jQuer开发者_如何转开发y code:
$.post('php/captcha.php', $('#captchaPost').serialize(), function(data){
if(data != "Valid")
{
$('#captchaError').show();
$captchaFlag = "Invalid";
}
else
{
$('#captchaError').hide();
$captchaFlag = "Valid";
}
});
And this PHP code for the post handler:
<?php
require_once('recaptchalib.php');
$privatekey = "1234567890";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_REQUEST["recaptcha_challenge_field"],
$_REQUEST["recaptcha_response_field"]);
if (!$resp->is_valid)
{
// What happens when the CAPTCHA was entered incorrectly
echo "Error";
}
else
{
echo "Valid";
}
?>
I checked the response using Firebug and the PHP script always returns "Error", even when I type in the correct Captcha. The form seems to POST correctly, according to the server, although I don't see how to check what was posted in the form. I am not using the PHP function to build the reCaptcha form; I got the HTML from Google's docs on this. Any help?
Try using this code:
function validateCaptcha()
{
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
var html = $.ajax({
type: "POST",
url: "php/captcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if(html != "Valid")
{
$('#captchaError').show();
$captchaFlag = "Invalid";
}
else
{
$('#captchaError').hide();
$captchaFlag = "Valid";
}
}
It doesn't look like you were sending the data correctly in your jQuery.
Edit Also make sure to call validateCaptcha() on the button. For instance:
onSubmit="javascript:validateCaptcha()"
精彩评论