Basj Basj - 7 months ago 80
Javascript Question

"Not a robot" recaptcha without a <form> but AJAX instead

The traditional way of using "I am not a robot" Recpatcha seems to be with a

<form>
on client-side:

<form action="post.php" method="POST">
<div class="g-recaptcha" data-sitekey="6Lc_0f4SAAAAAF9ZA_d7Dxi9qRbPMMNW-tLSvhe6"></div>
<button type="submit">Sign in</button>
</form>

<script src='https://www.google.com/recaptcha/api.js'></script>


Then some
g-recaptcha-response
will be sent to server.




However, in my code I don't use a
<form>
but an AJAX call instead:

$('#btn-post').click(function(e) {
$.ajax({
type: "POST",
url: "post.php",
data: {
action: 'post',
text: $("#text").val(),
ajaxMode: "true"
},
success: function(data) { },
error: function(data) { }
}); } });


**How to get the
g-recaptcha-response
answer with this solution?

Answer

You use a form, interrupt the submissions of the form. Set up a form as per normal:

<form action="post.php" method="POST" id="my-form">
    <div class="g-recaptcha" data-sitekey="6Lc_0f4SAAAAAF9ZA_d7Dxi9qRbPMMNW-tLSvhe6"></div>
    <input type="text" id="text">
    <button type="submit">Sign in</button>
</form>

<script src='https://www.google.com/recaptcha/api.js'></script>

And then you use jQuery to interrupt the submission of the form and serialize it, allowing you to pass the data through Ajax:

$('#my-form').submit(function(e) {
    e.preventDefault();
    $this = $(this);
    $.ajax({
        type: "POST",
        url: "post.php",
        data: $this.serialize()
    }).done(function(data) {
    }).fail(function( jqXHR, textStatus ) {
        alert( "Request failed: " + textStatus );
    });
});

As you will have noticed I've used .done and .fail instead of success and error, this is the preferred way of handling the response.