I want to include google recaptcha in my login page.
Normally, I collect variables from various inputs and sent them using ajax
to prologin.php
for proccessing.
But don't know how to get response of clicked
captcha, what kind of responses are possible (true
, false
, or... what ?), to proccess them also.
login.php
<script src='https://www.google.com/recaptcha/api.js'></script>
<input type='text'...>
<input type='checkbox'...>
<div class="g-recaptcha" data-sitekey="6Ld..."></div>
<div id='btnlogin'>LOGIN</div>
login.js
$('#btnlogin').click(function(){
var a = ...;
var b = ...;
var captchaResponse = ...; // what ?
$.ajax({
url: 'prologin.php',
...
});
Any help?
You have to use grecaptcha.getResponse()
to get the user's response. And as a sidenote, use grecaptcha.reset()
to ask the end user to verify with reCAPTCHA again.
$('#btnlogin').click(function(){
var a = ...;
var b = ...;
var captchaResponse = grecaptcha.getResponse();
$.ajax({
url: 'prologin.php',
...
});
...
});
Here's the reference: https://developers.google.com/recaptcha/docs/verify
AJAX:
$('#btnlogin').click(function(){
var a = ...;
var b = ...;
var captchaResponse = grecaptcha.getResponse();
$.ajax({
type: 'POST',
url: 'prologin.php',
data: {a: a, b: b, captchaResponse: captchaResponse};
success: function(data) {
// reset the reCaptcha
grecaptcha.reset();
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
...
});
prologin.php
<?php
//your site secret key
$secret = 'YOUR_SECRET_KEY';
if(isset($_POST['captchaResponse']) && !empty($_POST['captchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['captchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
}else{
// failure
}
}
?>
Google recaptcha's response is sent with name g-recaptcha-response
. This is also class name and ID for an input (textarea). So you can try any of these:
$('#g-recaptcha-response').val();
$('form .g-recaptcha-response').val();
$('form [name="g-recaptcha-response"]').val();