Integrate reCAPTCHA verification using Ajax
Guys, Today I will discuss Google reCaptcha verification on this topic. reCAPTCHA is a CAPTCHA-like system that checks a computer user is human or not. In this tutorial, I will show you a step of form reCAPTCHA verification.
First, create a form in your web page and define a captcha box, where user introduces human or a robot. I also put an example code below of this text, use this form on your website. It doesn’t work without Google reCAPTCHA API. To solve it, use a js link on your web page. Follow the example code:
Form Example:
<form> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <div class="form-group"> <span id="ErreCCaptcha" style="color: red; background:#ffffff"></span> <div class="g-recaptcha review-re" data-sitekey="your site key"></div> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <button style="z-index: 0;" type="button" class="tg-btn" onclick="submit_data();">Submit</button> </div> </form>
JS LINK:
//Js Link <script src='https://www.google.com/recaptcha/api.js'></script>
When user click submits button after clicking the CAPTCHA Box, the data pass a PHP page using Ajax. In the PHP page check, whether the user introduced a human or a robot?
If it gets success so it returns success value for the next work. If it returns the error so display an error message to the user for reCAPTCHA the form.
AJAX CODE:
<script> function submit_data(){ var recaptcha= grecaptcha.getResponse(); $.ajax({ type:"post", url:"<?php echo SITE_URL;?>data_insert.php", data:{recaptcha:recaptcha}, success:function(res){ if(res=="error"){ $("#ErreCCaptcha").text('Please click on the reCAPTCHA box'); } console.log(res); } }); } </script>
PHP CODE:
<?php include("dbconnect.php"); if(isset($_POST['recaptcha']) && !empty($_POST['recaptcha'])){ //your site secret key $secret = 'your site secret key'; //get verify response data $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['recaptcha']); $responseData = json_decode($verifyResponse); if($responseData->success){ echo 'success'; }else{ echo "error"; } } ?>
how u have done comment section with recaptcha . if I press submit button without checking I’m not a robot form should not sumit. Please suggest how to do this
very useful and in todays time its very important to have captcha on our website . so we can ignore the bots ..