Google reCaptcha response “Uncaught (in promise) n

2020-08-09 07:28发布

I'm use reCaptcha v2 but in dev console response Uncaught (in promise) null in in any case (and moving the .reset() function)

console:

enter image description here

my code for recaptcha:

<div class="text-xs-center" style="text-align: center; height:150px;">
    <p style="color: black;"> Complete the verification: </p>
    <div style="display: inline-block;" class="g-recaptcha" data-sitekey="xxxxxxxxxxx" data-callback="callback"></div>
</div>

my callback function:

function callback() {
    if (grecaptcha === undefined) {
        alert('Recaptcha non definito'); 
        return; 
    }

    var response = grecaptcha.getResponse();
    console.log(response);

    if (!response) {
        alert('Coud not get recaptcha response'); 
        return; 
    }

    $.ajax({
    'url' : 'validate-recaptcha.php',
    'type' : 'POST',
    'data' : {
        'response' : response   
    },
    'success' : function(data) {              
        alert('Data: '+data);
    },
    'error' : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
    });
    grecaptcha.reset();
}

and my validate-recaptcha.php:

<?php
//debug
$fp = fopen('debug.txt', 'a');
fwrite($fp, print_r($_POST, TRUE));
fclose($fp);
//enddebug

if (empty($_POST['recaptcha'])) {
    exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(
    array (
        'response' => $response,
        'secret' => 'yoursecretkey',
        'remoteip' => $_SERVER['REMOTE_ADDR']
    )
);
$opts = array('http' => 
    array (
        'method' => 'POST',
        'header' => 'application/x-www-form-urlencoded',
        'content' => $post
    )
);
$context = stream_context_create($opts);
$serverResponse = @file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if (!$serverResponse) {
    exit('Failed to validate Recaptcha');
}
$result = json_decode($serverResponse);
if (!$result -> success) {
    exit('Invalid Recaptcha');
}
exit('Recaptcha Validated');

Searching on the internet, probably the problem is the .reset() function, but I do not understand the solution.

9条回答
贪生不怕死
2楼-- · 2020-08-09 07:56

I had this issue. It was because in my callback function jquery code was there and for some reason, I had forgotten to include the jquery script. So if you are having this issue, I suggest you to carefully go through each line of your call back code. May be reduce the complexity line by line and you will get the solution. The error handling should have been done in a better way.

查看更多
甜甜的少女心
3楼-- · 2020-08-09 07:58

In my case I was using jquery.3.4.1.slim.js then I changed to jquery.3.4.1.min.js and the error disappeared. I'm on ASP.NET WebForms .

查看更多
家丑人穷心不美
4楼-- · 2020-08-09 07:59

Another trigger for this error that plagued me was having a button in the form with a name attribute of 'submit'. If using the automatic binding example code from the reCaptcha documentation, this will trip it up, since 'form.submit' will refer to the button rather than the submit() function of the form itself. Doh!

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
     <script>
       function onSubmit(token) {
         document.getElementById("demo-form").submit();
       }
     </script>
  </head>
  <body>
    <form id='demo-form' action="?" method="POST">
      <!-- Oops.... avoid the name="submit" below -->
      <button name="submit" class="g-recaptcha" data-sitekey="your_site_key" data-callback='onSubmit'>Submit</button>
      <br/>
    </form>
  </body>
</html>
查看更多
ら.Afraid
5楼-- · 2020-08-09 08:04

Recaptcha v2 callback js error

I had this error too and I found is related with the recaptcha callback (in your case data-callback="callback"). If you remove your data-callback attribute the error won't come up.

The console error Uncaught (in promise) null indicates the callback is waiting for a promise. Here's a basic callback function for recaptcha using promises:

function callback() {
    return new Promise(function(resolve, reject) { 

    //Your code logic goes here

    //Instead of using 'return false', use reject()
    //Instead of using 'return' / 'return true', use resolve()
    resolve();

  }); //end promise
};

In your case you need to adjust your code to something like this:

function callback() {
  return new Promise(function(resolve, reject) {  

    if (grecaptcha === undefined) {
        alert('Recaptcha non definito'); 
        //return;
        reject();
    }

    var response = grecaptcha.getResponse();
    console.log(response);

    if (!response) {
        alert('Coud not get recaptcha response'); 
        //return;
        reject();
    }

    $.ajax({
    'url' : 'validate-recaptcha.php',
    'type' : 'POST',
    'data' : {
        'response' : response   
    },
    'success' : function(data) {              
        alert('Data: '+data);
        resolve();
    },
    'error' : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
        reject();   
    }
    });
    grecaptcha.reset();

  }); //end promise
}

This is my first answer in SO, so please be patient and let me know if I forgot or missed something :)

查看更多
放荡不羁爱自由
6楼-- · 2020-08-09 08:08

I feel I should add an answer here with my specific experience. I give credit to the top answer, which will be part of my answer.

I was getting: Uncaught (in promise) null. When I expanded the error in the console it was empty.

I changed my code from this:

function onSubmit(token) {
    if (grecaptcha.getResponse() !== "") {
        $('#request-form').submit();
    }
    grecaptcha.reset();
}

To this:

function onSubmit(token) {
    return new Promise(function (resolve, reject) {

        if (grecaptcha.getResponse() !== "") {
            $('#request-form').submit();
        }
        grecaptcha.reset();

    });
}

What this change does is allows you to receive a specific error message in your console. You can then proceed to fix your specific problem.

查看更多
混吃等死
7楼-- · 2020-08-09 08:08

In my case, my callback just referenced some variable that didn't exist and I saw the same error. Very weird error for something so simple!

I also saw the same error when I left a . after a variable name on accident. Seems like this is a super generic error that means fix the code in your callback!.

查看更多
登录 后发表回答