In my index.php page I include the Recaptcha script in my header:
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
And in my index.php page I load my homeindex.php using:
function loadHome() {
$('#homedynamic').load('php/homeindex.php');
}
Now my homeindex.php page contains the following code (simplified):
<script>
$(document).ready(function() {
Recaptcha.create("6LfqWeYSAAAAAFStYfL9gsCJ5BFWO60sn4CKbwjj", recaptcha_div, {
theme: "clean",
callback: Recaptcha.focus_response_field});
});
</script>
<script>
function aanmelden() {
vcaptcha = $("#recaptcha_response_field").val();
vchallenge = $("#recaptcha_challenge_field").val();
$.ajax({
type: "POST",
dataType: "json",
data: { captcha:vcaptcha, challenge:vchallenge },
url: './query/aanmelden/aanmelden.php',
success: function(result) {
if (result.status == 0) {
alert (result.omschrijving);
}
if (result.status == 1) {
//success
}
}
});
}
</script>
<div class="right">
<div id="recaptcha_div"></div>
<div><button id="aanmelden" type="submit" onClick="aanmelden()">X</button>
</div>
</div>
And I've got an aanmelden.php page:
<?php
function returnResult($status, $omschrijving){
$result = array(
'status' => $status,
'omschrijving' => $omschrijving
);
echo json_encode($result);
exit();
}
require_once 'recaptchalib.php';
require_once '../../php/connect.php';
$privatekey = "6LfqWeYSAAAAAEH6OrMYD9qJ0SfcWkePTPi99CrZ";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
$status = 0;
$omschrijving = "Captcha is niet correct";
returnResult($status, $omschrijving);
} else {
$status = 1;
$omschrijving = "Captcha is correct";
returnResult($status, $omschrijving);
}
?>
So I checked that the captcha shows, the input values are passed correctly to the aanmelden.php page... But it doesn't return anything back. My aanmelden.php page works fine. I used the function returnResult with success. The only thing I noticed is that if I comment these lines:
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
It does return a status and omschrijving for my other checks. But with these lines active, it somehow doesn't work...
Anybody knows why? Also, recaptchalib.php is on the right location...
I got it working!
Somehow, I made the mistake of using the wrong POST[] field. And I also added Recaptcha.reload(); if a user does make a mistake.
You should hide you secret value (that you exposed in your question) at any cost.
Anyone with this information can hack your captcha, easily.
If you plan to use this validation on a public site, I suggest you to recreate it at google recaptcha page.