Trying to get my form which uses google invisible recaptcha to work correctly with my my jQuery AJAX and PHP. From my research it seems that the token is not being sent to my PHP page correctly via AJAX. Keep getting the Error below from my PHP page when form is submitted.
array(2) {
["success"]=>
bool(false)
["error-codes"]=>
array(1) {
[0]=>
string(22) "invalid-input-response"
}
}
My HTML / jQuery Code Below
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<style>
.grecaptcha-badge {
display: block;
float: left;
}
</style>
</head>
<body>
<form id="myForm">
<div>First Name*</div>
<div><input id="first_name" name="first_name" required="" type="text"></div>
<!--<span class="form-error">Please enter your first name.</span>-->
<div>Last Name*</div>
<div><input id="last_name" name="last_name" required="" type="text"></div>
<!--<span class="form-error">Please enter your last name.</span>-->
<button class="g-recaptcha" data-sitekey="6Ld1..." data-callback="onSubmit">submit</button>
</form>
<div id="status"></div>
<script defer>
function onSubmit(token) {
var f = $("#myForm");
$.ajax({
type: "POST",
url: "request.php",
data: f.serialize(),
dataType: "json",
beforeSend: function() {
$("#status").html("submitting data...");
},
success: function(response) {
$("#status").html(response.text);
if (response.type == "success") {
window.location.replace("/myaccount");
} else {
$("#status").html("Captcha failed.");
}
},
error: function() {
$("#status").html("Failed.");
}
});
}
</script>
</body>
</html>
My PHP code which is not handling the token correctly is below
<?php
if(isset($_POST['g-recaptcha-response'])) {
$result = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=['secret key']&response=$_POST["g-recaptcha-response"]&remoteip=$_SERVER["REMOTE_ADDR"]'), TRUE);
//echo 'success';
if($result['success'] == 'true') {
// Captcha ok
echo 'success';
} else {
// Captcha failed
echo 'failed';
}
var_dump($result);
}
?>
Thanks in advance! The reCAPTCHA documentation really sucks....