80

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.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
FABBRj
  • 962
  • 1
  • 9
  • 21
  • 1
    I've got `Uncaught (in promise) null` error due to call to undefined function inside the callback function specified for reCaptcha. If you have this kind of error carefully review your callback function first. – Pavel Ivanov Jan 19 '19 at 16:50
  • 1
    try this .. [Google Recaptcha Demo](https://stackoverflow.com/questions/63727575/google-recaptcha-v3-recaptcha-response-is-null/65825466#65825466) – Mohit RaiYani Jan 21 '21 at 10:40

11 Answers11

76

Turns out it also occurs when a site is not "registered" in the Google recaptcha/admin Domains area.

Solution: Add the domain in the recaptcha admin area:

  1. Sign into your Google account where your recaptcha keys are registered
  2. Type into Google "google recpatcha admin console"
  3. Go to your settings for your (production) key
  4. In "Domains", add these two entries:
localhost
127.0.0.1
  1. Save it and test your recaptcha.

I made this error when I switched from a development key to a production key. The production key did not have any entries for localhost.

I configured the API response to sit behind a proxy-redirect. Therefore the verification was working in a localhost environment which was not configured in the Google Admin console which caused this generic error.

Credit to @Christian Žagarskas who pointed it out in his comment.

EliteRaceElephant
  • 7,744
  • 4
  • 47
  • 62
32

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 :)

Behzad
  • 3,502
  • 4
  • 36
  • 63
EsaulFarfan
  • 471
  • 5
  • 9
  • Unfortunatelly, this solutions seems not to work for me. I managed to rewrite my callback to promise variant, it works but that error " uncaught exception: Request timed out." still appears, – Radek Svítil Nov 08 '18 at 13:19
  • @radeksvitill I think you have a second error outside of the scope of this answer. – EsaulFarfan Nov 17 '18 at 05:27
  • 7
    I had the same problem here, I did not have a callback to begin with... but started getting this error one day... For the sake of Posterity: Turns out it also occurs when a site is not "registered" in the Google recaptcha/admin Domains area. After 30 min suddenly it worked again, turns out I had to add www.mysite, dev.mysite and mysite as 3 separate allowed domains. (I had not yet added the dev subdomain and *.mydomain wildcards do not work) So... might want to double check the admin settings. I also had htaccess password protecting my domain, turned that off too... – Christian Žagarskas Nov 24 '18 at 01:35
  • onCompleted = function(response) { console.log('captcha completed.'); $("#formContact").submit(); return true; }; this is my callback, i get the same error, can anyone help with this one? – Termatinator Jun 05 '19 at 12:53
  • 1
    @Termatinator use the HTML attribute "data-callback" like I explain above instead of using the "onCompleted" javascript event ;) – EsaulFarfan Jun 11 '19 at 05:15
  • @EsaulFarfan the exact error: anchor?ar=1&k=6LdHKaMUAAAAAO3BkeFXeKjwNiHqP6r4UttkmGzS&co=aHR0cDovL3d3dy5jZWVkZWV3aW5rZWwubG9jYWxob3N0Ojgw&hl=nl&v=v1559543665173&size=invisible&cb=j8dcjceh8cnl:1 Uncaught (in promise) null – Termatinator Jun 11 '19 at 06:48
  • @Termatinator I think it could be another problem then. I can suggest you to open a new question so you can add there your code and I can check it along with other people. If you do so, please mention me there or here, so that I can follow up your question. Oh and please include screenshots as possible :) – EsaulFarfan Jun 12 '19 at 04:54
  • keep scrolling to the answer by @EliteRaceElephant – Tristanisginger Jul 09 '19 at 13:00
  • your solution was perfect in my case! – Patricio Jofre Dec 17 '19 at 19:44
  • I don´t have a callback attribute on my site but I also get the error. I figured out that the error does not show up when I clear my browser cache. – Franz Deschler Sep 16 '20 at 11:41
30

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>
John Rix
  • 6,271
  • 5
  • 40
  • 46
9

This can happen when your callback code causes an error. 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!.

Trev14
  • 3,626
  • 2
  • 31
  • 40
  • 1
    what if your callback is in someone else's plugin code? – Scott Feb 14 '19 at 19:51
  • 1
    This is the error I saw. In more general terms, the error message occurs if the callback has an error. So if debugging this, try to reduce the callback to a simple `console.log('callback called')` to see if that makes it work. – mahemoff Nov 01 '19 at 22:02
  • 2
    The other answers didn't help me, this one did. Turns out I had a silly error (typo) in my callback function. Apparently the Google reCAPTCHA callback is promise based and this obscures the "real" problem, you just don't get a decent stacktrace. After carefully reading and re-reading my callback function, and after spotting and fixing the bug/error, this obscure message “Uncaught (in promise) null” went away. – leo Mar 31 '20 at 17:00
8

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.

KidBilly
  • 3,408
  • 1
  • 26
  • 40
  • 1
    this helped me a ton! thank you so much. I thought this was some weird recaptcha error, but it turned out I had an undefined variable – good_afternoon Feb 13 '20 at 20:39
2

Similar to John Rix issue/solution. I also got the error when the id of the submit element was 'submit'.

<!-- Avoid id="submit" below -->
<input type="submit" id="submit" value="submit">```
epluribusunum
  • 125
  • 2
  • 15
2

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 .

Máster
  • 981
  • 11
  • 23
1

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.

Prashant Onkar
  • 414
  • 3
  • 15
1

I was using ASP.NET Core 3.1 Identity, I had this issue and solved it by updating jquery.validate.min.js and jquery.validate.unobtrusive.min.js to the latest version in _ValidationScriptsPartial.cshtml.

Wael Alshabani
  • 1,495
  • 1
  • 15
  • 16
1

I had the same issue and the problem was that I didn't add localhost to the list of supported domains.

Mimoid
  • 722
  • 1
  • 10
  • 25
0

I hit this error because I had:

const onChange = e => {
  e.preventDefault();
  console.log('success')
}

<ReCAPTCHA sitekey="yeet" onChange={onChange} />

Removing e.preventDefault() removed the error.

duhaime
  • 25,611
  • 17
  • 169
  • 224