Implementing Google reCaptcha in WordPress AJAX Register

Thanks to all visitors for their love to the article http://fellowtuts.com/wordpress/wordpress-ajax-login-and-register-without-a-plugin/. As we got many requests to implement Google reCaptcha in WordPress AJAX Register, I’m here with the wonderful code which will protect spams through Google reCaptcha during registration in your WordPress powered site.

The steps are same as previous article and again you can download zip at end of post and implement them. I would suggest you to read that post first because I’m focusing here just on what is running behind user reCaptcha validation.

Google reCaptcha in WordPress AJAX Register

Implementing Google reCaptcha in WordPress AJAX Register

To add reCaptcha validation, you must have Google site key and secret key. You can get it from here or you can follow the steps in this article to obtain keys.

The Form

Create a file ajax-auth.php inside your active theme’s directory and put the code given below in that.

Here before submit button we placed a div to produce reCaptcha block in our registration form. The lines added as compared to previous article are highlighted. Don’t forget to place your site key at “GOOGLE SITE KEY“.

As now we need to show Login and Signup buttons somewhere in out site so place the code below in your theme file wherever you wish them to appear:

CSS

Under your current theme’s css directory, you need to create a file called ajax-auth-style.css with this code below. This is almost same as the CSS mentioned in previous article. Only changes are made highlight. 

Sending user info via AJAX

This is the tricky JS part which is required to let our recaptcha functionality work during registration and it’s also responsible for client side validation, sending AJAX request and process according to response received from server.

jquery.validate.js and ajax-auth-script.js, both are necessary to perform. Put both files in js folder in your active theme. The imprioved code for ajax-auth-script.js is as follow:

Here, two additional things are important to note.  First, we are sending recaptcha variable with data object at form submission which is empty during login and filled by value of “g-recaptcha-response” field during registration. This field is being populated automatically by Google reCaptcha API script which we are going to add in our page just a moment later.

Second, based upon response from server, the reCaptcha is being reset if registration is failure as because you can’t submit the same recaptcha twice otherwise server will say “reCAPTCHA invalid” at next time.

Finally we need a regular login/signup server side handler along with some code to validate if reCaptcha is checked/filled & valid and process accordingly. The PHP script below does the rest of the task which is saved as custom-ajax-auth.php inside libs folder in active theme.

This is time to use your Google secret key and validate the reCaptcha response returned by user using curl. We used WordPress’s “wp_enqueue_script” function to add Google  reCaptcha API script in our page, which shows a nice reCaptcha form above our signup submit button.

Inside “ajax_register” function there is code block to validate the reCaptcha entered by user with Google and successfully implementing Google reCaptcha in WordPress AJAX Register. Just not forget to replace “GOOGLE SECRET KEY” with your actual secret key you obtained from Google.

You can now perform a validation prior to registration if the user is a human and is not a robot with AJAX feature in WordPress AJAX login and register.

Download Zip

Included: ajax-auth-style.css, jquery.validate.js, ajax-auth-script.js, ajax-auth.php, custom-ajax-auth.php

You Might Interested In

39 COMMENTS

  1. Nicholas Borthwick says:

    I think this is among the most vital info for me. And i am glad reading your article. But should remark on some general things, The website style is perfect, the articles is really nice : D. Good job, cheers

    Reply
  2. Florene Hutchinson says:

    I got this web page from my buddy who told me concerning this website and now this time I am browsing this site and reading very informative content at this place.

    Reply
    1. Amit Sonkhiya says:

      Hi @burakmeteerdoan:disqus

      The steps are quite similar to the same implement for the Registration. The only glitch is you can’t use two Recaptcha on the same page (Login and Registration). I would suggest you to take some help of jQuery and shift wherever require.

      Also, you need upgrading code for the client as well as the server. Please inspect what I have provided and try to do the same.

      In case, you feel it difficult to implement, please write us to amit[at]astech[dot]solutions

      Reply
  3. Ojasya Thakur says:

    hi Amit .. Thanks for the script and great explanation but some how its not working if in case there is some error like 1) email exists or 2) username exists etc

    it just gets struck on Sending user info, please wait…”Sending user info, please wait…”

    Reply
    1. Amit Sonkhiya says:

      Hello @ojasyathakur:disqus

      If you’re stuck at Sending user info then it means that the AJAX request isn’t being fired properly. Please check the request from developer console in the browser.

      Reply
      1. Ojasya Thakur says:

        @amitsonkhiya:disqus Hi again. thanks for the prompt reply ..
        I am not sure how to do that but I did try and check response in developer console > networks .. (http://tinyurl.com/yy6racqj)

        I am getting response that “username already exists” . even captcha refreshes — its just that text “Sending user info, please wait…” never refreshes .. so confusing for a user .. ..

        Looking forward for you reply

        Reply
        1. Amit Sonkhiya says:

          Hello @ojasyathakur:disqus

          I’m doubtful that there is a little issue in the line #65 in ajax-auth-script.js here.

          Can you replace
          $('p.status', ctrl).text(data.message);
          with
          $('p.status').text(data.message);
          and test again?

          Reply
          1. Ojasya Thakur says:

            @amitsonkhiya:disqus
            thanks for getting back..

            Actually yeah I figured out that one as I looked the comments below and it worked perfect . now I again hit roadblock. when I change v2 captcha to V3

            nowI am getting this — “ERROR for site owner: Invalid key type”..

            will this not work with v3 or is there some other issue

  4. Sultan Khan 3 says:

    hello Amit , thanks for your high quality tutorials . is there possible to integrate this ajax script with google sign in / sign up feature?! thank you .

    Reply
    1. Amit Sonkhiya says:

      Hello @Sultan Khan

      It’s indeed possible to Integrate social login with AJAX script. However, you need having good technical knowledge to accomplish it including Google Sign In API, WordPress, PHP and jQuery.

      Reply
    1. Amit Sonkhiya says:

      Yes, it’s possible.
      Do the same things as shown here, just in the code for Forget Password.
      Additionally, move the server side validation code in the ajax_register() function (line no #48 to #74) to another function and call that new function in ajax_register() as well as ajax_forget() to validate the Recaptcha.

      Reply
      1. ADv says:

        It’s clear, but we have such code

        success: function(data) {
        jQuery(‘p.status’, ctrl).text(data.message);
        if (data.loggedin == true)
        document.location.href = ajax_auth_object.redirecturl;
        else if (ctrl == ‘register’)
        grecaptcha.reset();
        }

        for registration form. How would we validate correct answer if in Forgot Password we have only

        success: function(data) {
        jQuery(‘p.status’, ctrl).text(data.message);
        }

        What should be the statement instead of ” if (data.loggedin == true) “. What to check?

        Reply
      2. ADv says:

        It’s clear, but we have such code

        success: function(data) {
        jQuery(‘p.status’, ctrl).text(data.message);
        if (data.loggedin == true)
        document.location.href = ajax_auth_object.redirecturl;
        else if (ctrl == ‘register’)
        grecaptcha.reset();
        }

        for registration form. How would we validate correct answer if in Forgot Password we have only

        success: function(data) {
        jQuery(‘p.status’, ctrl).text(data.message);
        }

        What should be the statement instead of ” if (data.loggedin == true) “. What to check?

        Reply
        1. Amit Sonkhiya says:

          I haven’t tested code for multiple Recaptcha fields on the same page. You can use either separate Recaptcha fields and validate the used one or use the same field for both forms using JS.

          Hope, these two articles could assist you to go in right direction. Still if any issue persists, don’t hesitate to revert.

          http://mycodde.blogspot.com/2014/12/multiple-recaptcha-demo-same-page.html
          https://stackoverflow.com/questions/1241947/how-do-i-show-multiple-recaptchas-on-a-single-page

          Reply
  5. Athar K says:

    Hi Amit,

    Indeed a very nice piece of work. But unfortunately, I am unable to get this work for me. I have implemented exactly as described but upon clicking on sign up or login links, the background becomes Grey and nothing else happens. No pop up is displayed to register or login. Can you please guide me as what could be the cause of this issue? Issue image is attached below.

    https://uploads.disquscdn.com/images/aeb100f125531af8e7c83936390220ced79a7ae244cfebebef910392ce0e06ff.jpg

    Thanks.

    Reply
  6. Zeckart says:

    I had a probleme, the error message aren’t displaying. (i have the same probleme than
    #comment-2469317715 ):
    “. The reCaptcha is implemented with Register but the P.Status only shows Sending user info, please wait… when i tried to console it, the response was {“loggedin”:false, “message”:”Please enter reCaptcha”} but it doesn’t replaces on the P.Status div. ”

    I have find a solution but i don’t know what was the probleme with “ctrl”

    On the file: ajax-auth-script.js

    I change this line (65)
    $(‘p.status’, ctrl).text(data.message);
    with this
    $(‘p.status’).text(data.message);

    And now it’s work.

    Reply
    1. Amit Sonkhiya says:

      @Zeckart thank you for sharing and glad you solved it. I will recheck the issue at later time as it’s not appearing in my browser.

      Reply
  7. Dawid Adach says:

    Hi Amit,
    Thanks for great tutorial. Do you consider extending it with description on how to add verifying email with confirmation link? That would be awesome! 😉

    Reply
  8. ///\/// says:

    Hi Amit,

    I have implemented this updates with your all updates in one i.e. login, register and forgot password on the page rather than popup. The reCaptcha is implemented with Register but the P.Status only shows Sending user info, please wait… when i tried to console it, the response was {“loggedin”:false, “message”:”Please enter reCaptcha”} but it doesn’t replaces on the P.Status div. And once i am able to logged in, it still doesn’t show Successful, Redirecting….

    Something tiny thing is missing. Please help

    Reply
  9. Dawid Adach says:

    Hi Amit,
    I have implemented your code however it doesn’t work fine for me. When I try to register without confirming captcha I am getting error “Please enter reCAPTCHA” as expected. But when I click on captcha checkbox, google verifies my identity but I am still getting the same error. Do you have any clue where should I look for?

    I checked my site using firebug and what I found is that g-recaptcha-response doesn’t get any value after sumbiting and thats probably why validation is failing…

    Reply
    1. Dawid Adach says:

      Actually I found that isn’t an issue. I am alerting out field value:

      recaptcha = $(‘#g-recaptcha-response’).val();
      alert(recaptcha);

      And I can see that it has some content (random string of carachters) so for some reason PHP part doesn’t recognize it…

      Reply
    2. Dawid Adach says:

      I found the issue, I was adjusting existing code from previous tutorial, so I changed all highlighted parts, however in ajax-auth-script.js line 61 isn’t highlighted therefore I missed it: (‘recaptcha’: recaptcha)

      Reply
  10. tanvir says:

    Hi, I have implement is accurately. It is nice, but it doesn’t work on my site. When I click on I’m not roboot, recaptacha popup and invalided and then when I click on register, it returns enter recaptcha. help plz.

    Reply

Leave a Reply