I've had a look at this question
How to Validate Google reCaptcha on Form Submit
And tried to implement the answer of that question into my code to validate my form so that it won't submit if the captcha hasn't been completed.
However nothing happens - it just submits the form.
this is my code:
<head>
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : 'my_site_key'
});
};
</script>
</head>
<div id="html_element"></div>
<br>
<input type="submit" value="Submit" onclick="myFunction">
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
function myFunction() {
if(grecaptcha.getResponse() == "")
alert("You can't proceed!");
else
alert("Thank you");}
</script>
Can anyone help?
EDIT
<html>
<head>
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : 'site-key'
});
};
onloadCallback();
$('form').on('submit', function(e) {
if(grecaptcha.getResponse() == "") {
e.preventDefault();
alert("You can't proceed!");
} else {
alert("Thank you");
}
});
</script>
</head>
<body>
<form action="?" method="POST">
<div id="html_element"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
</script>
</body>
You need to trigger your if
statement in an event. If you're using jQuery you can do this very easily:
$('form').on('submit', function(e) {
if(grecaptcha.getResponse() == "") {
e.preventDefault();
alert("You can't proceed!");
} else {
alert("Thank you");
}
});
See working example here: JSFiddle
The problem with doing this in JavaScript at all is that the user can easily fake the result if they want to. If you really want to be checking if the user is a robot or not, you should still be comparing the result submitted by the user (via POST) on the server side using your reCAPTCHA secret key.