Recaptcha send form Jquery post?

Recaptcha send form Jquery post?

If you want to use recaptcha with a jquery code, let’s say you have a form with inputs, and a recaptcha.

You want to submit the form without refresh, so the recaptcha will go trough jquery/ajax.

Here is an example:

The form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<form name="contact" action="javascript:void(0);" method="post" enctype="multipart/form-data" class="form-horizontal">
 
<div class="form-group">
<label for="name" class="control-label col-lg-2">
Name
</label>
<div class="col-lg-10">
<input type="text" name="name" id="name" class="form-control" placeholder="Name">
</div><!--end col-lg-10-->
</div><!--end form group-->
 
<div class="form-group">
<label for="email" class="control-label col-lg-2">
Email
</label>
<div class="col-lg-10">
<input type="text" name="email" id="email" class="form-control" placeholder="Email">
</div><!--end col-lg-10-->
</div><!--end form group-->
 
<div class="form-group">
<label for="message" class="control-label col-lg-2">
Message
</label>
<div class="col-lg-10">
<textarea name="message" id="message" class="form-control" cols="20" rows="10" placeholder="Your Message"></textarea>
</div><!--end col-lg-10-->
</div><!--end form group-->
 
<div class="form-group">
<label for="recaptcha" class="control-label col-lg-2">
Antispam
</label>
<div class="col-lg-10">
<div class="g-recaptcha" data-sitekey="_recaptcha key goes here_"></div>
</div><!--end col-lg-10-->
</div><!--end form group-->
 
 
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="submit" class="btn btn-md btn-primary" id="btn_submit">Send</button>
</div><!--end col-lg-offset-->
</div><!--end form group-->
 
</form>

The Jquery code:

2
3
4
5
6
7
8
9
10
11
<script>
$(document).ready(function(){
$("#btn_submit").click(function(){
	var name = $("#name").val();
	var email = $("#email").val();
	var message = $("#message").val();
	$("#return_message").load("contact-process2.php", {name : name, email : email, message : message, captcha: grecaptcha.getResponse()});
});
});
</script>

The php process file that will check recaptcha:

3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
if(isset($_POST['captcha']) && !empty($_POST['captcha'])){
    //your site secret key
    $secret = '...';
    //get verify response data
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['captcha']);
    $responseData = json_decode($verifyResponse);
    if($responseData->success)
             {
 
//run your code from here
 
}
else{ exit; }

If you have any questions, please leave in the comments.

Add a comment: