-
-
Save virtuosomaster/c288a0bd991613943edad2aa020194c7 to your computer and use it in GitHub Desktop.
How to create custom form with google captcha using AJAX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function custom_form_callback( $atts ) { | |
?> | |
<form id="form" method="POST" action=""> | |
<input type="text" name="name" class="name" placeholder="Full Name" required="required"> | |
<div class="g-recaptcha" data-sitekey="my-google-site-key" data-callback="enableBtn"></div> | |
<input id="submit" type="submit" name="submit" value="Submit" disabled="disabled"> | |
</form> | |
<?php | |
} | |
add_shortcode( 'custom-form', 'custom_form_callback' ); | |
add_action( 'wp_ajax_captcha_checker', 'captcha_checker' ); | |
add_action( 'wp_ajax_nopriv_captcha_checker', 'captcha_checker' ); | |
function captcha_checker(){ | |
$recaptchaToken = $_POST['recaptchaToken']; | |
$secret = "yot-secret-key-here"; | |
$response = null; | |
$reCaptcha = new ReCaptcha($secret); | |
if ($recaptchaToken) { | |
$response = $reCaptcha->verifyResponse( | |
$_SERVER["REMOTE_ADDR"], | |
$recaptchaToken | |
); | |
if( $response->success ){ | |
$result = $response->success; | |
} | |
} | |
die(); | |
} | |
add_action('wp_footer', function(){ | |
?> | |
<script src='https://www.google.com/recaptcha/api.js'></script> | |
<script> | |
jQuery(document).ready(function($){ | |
$('#form').on('submit', function(e){ | |
e.preventDefault(); | |
var recaptchaToken = grecaptcha.getResponse(); | |
$.ajax({ | |
type:"POST", | |
data:{ | |
action : 'captcha_checker', | |
recaptchaToken : recaptchaToken | |
}, | |
url : nickelAjaxHandler.ajaxurl, | |
beforeSend:function(){ | |
// | |
}, | |
success:function(data){ | |
console.log(data) | |
} | |
}); | |
}); | |
}); | |
</script> | |
<?php | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment