Catch reCaptcha Value Google Ajax

Asked

Viewed 543 times

1

I am registering a form with Ajax, how to implement the use of reCaptcha?

<input type="text" name="email" id="email" class="form-control" placeholder="Email" required>
<div class="g-recaptcha" data-sitekey="bla,bla,bla"></div>
<input type="button" onclick="add_comment()" value="Enviar comentário" class="btn btn-primary pull-right"></button>

The Function 'add_comment()':

function add_comment() {
var url = 'comentarios/add_comment.php';
var method = 'POST';
params += '&email='+document.getElementById('email').value;
var container_id = 'comment-box' ;
var loading_text = '<img src="loader.gif">' ;
ajax (url, method, params, container_id, loading_text) ;
}

Setting an id in reCaptcha returns the value 'Undefined' The function works perfectly with registration, as I can send the value of reCaptcha to the function and validate it in the file . php?

Vlw

2 answers

2

Assuming the correct captcha value is in the "data-sitekey" attribute of the div ". g-recaptcha"

Maybe this will solve: (important: I am using jquery, make sure you have included the jquery library)

<input type="text" name="email" id="email">
<input type="text" name="captcha" id="captcha">
<div class="g-recaptcha" data-sitekey="bla,bla,bla"></div>
<input type="button" value="CADASTRAR" onclick="submitForm()">

function submitForm() {
  if( $('#captcha').val() == $('.g-recaptcha').attr('data-sitekey') ) {
    $.ajax{
        url: 'comentarios/add_comment.php',
        type: 'POST',
        data: {
            email: $('#email').val()
        },
        success: function( retornoPHP ) {
            alert('enviou');
        }
    }
  } else {
      alert('o captcha está incorreto');
  }
}

0

Doing it this way will work:

First we call the save function by sending the form.

$('#btn_salvar').click(function() {
            salvar($("#form_salvar")[0]);
        });

As we received the form and sent in this way:

function salvar(form) {
    $.ajax({
        url: "sua url aqui",
        method: 'POST',
        data: new FormData(form),
        contentType: false,
        cache: false,
        processData: false,
        success: function(data) {
            if (data.data) {
                location.reload();
            } else {
                console.log('falha ao enviar para o banco');
            }
        },
        error: function() {
            location.reload();
            console.log('alguma coisa deu errado no servidor..')
        }
    })
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.