In the tutorial, I will be using a working HTML contact form. We will submit it via AJAX (the page will not reload) and process the form values with PHP.
Google has released the new reCAPTCHA. They need just a single click to confirm they are not a robot. So, reCAPTCHA will protect your website from spam with better user experience. You can easily integrate Google reCAPTCHA in PHP script using ajax validation.
Header file Code
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
HTML Code
<form action="" method="POST" onsubmit="return validateForm(this);">
<input type="text" required="" class="text" value="" placeholder="Your name" name="name" >
<input type="email" required="" class="text" value="" placeholder="Email adress" name="email" >
<textarea type="text" placeholder="Message..." required="" name="message"></textarea>
<div class="g-recaptcha" data-sitekey=""></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
JavaScript / Jquery Code
<script>
function validateForm(form) {
var flag = 0;
var status = false;
var captcha = grecaptcha.getResponse();
if (captcha == '') {
flag = 1;
alert("please Select CAPTCHA !!");
}
if (flag == 1)
{
return status;
}
else
{
$.ajax({
type:'POST',
url:"submit.php",
data: {captcha: captcha},
dataType: 'JSON',
success:function(data){
if(data.status == 1)
{
status = true;
}
else
{
alert('CAPTCHA Time out');
status = false;
}
}
});
return status;
}
}
</script>
Call Ajax (Submit.php)
<?php
$secret = '';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['captcha']);
$responseData = json_decode($verifyResponse);
$json['success'] = $responseData->success;
echo json_encode($json);
?>