WordPress AJAX Login and Register without a Plugin

WordPress AJAX Login and Register without a Plugin

We can implement WordPress AJAX Login and Register without a Plugin. This tutorial will assist to let you do it in right manner with some additional features too, including

Best practice techniques
Both forms in popup windows
AJAX Login and Register without a Plugin
Inbuilt client side form validation with jQuery
Opening login/register form from link given in another popup

Update (January 12, 2015): I have written a post to add Forgot Password with AJAX functionality in code & steps mentioned here. Have a look over that tutorial too and download improved files there after reading this post.

So let’s do it right…

The Concept

There’s a couple of ways to implement login or register on your website. You could create separate Pages called Login and Register and display the form on empty pages with page-login.php and page-register.php templates respectively (kind of what you have by default when visiting /wp-admin). Another is to keep the forms visible all the time above the header or in the sidebar. Third and the option we are using here is to call a login/register box when you click on a given button/link. Moreever you can easily apply the AJAX technique given here on any concept you want.

IMPORTANT: Please note that if you have already installed any other AJAX Login plugin then ensure to deactivate that first.

The Form

We have created the both forms in a separate file called ajax-auth.php and called it for not logged in users using get_template_part() function in WordPress. Create a file ajax-auth.php inside your active theme’s directory and put the code given below in that.

The wp_nonce_field function creates a hidden field with ID “security” and value “ajax-login-nonce” in hashed form for login form. The same is acceptable for register form, a hidden field with ID “signonsecurity” and value “ajax-register-nonce”. We are using required and email classes to perform jQuery validation.

We also need login and signup buttons, so place that anywhere you want.

Styling the boxes

This is the required CSS that you have to put inside a new file called ajax-auth-style.css and place the file in css folder of your current theme.

Sending user info via AJAX

Next part is the “login” and “signup” buttons show our form, validate and send the form data with AJAX to the function (which we will define in the next and last step).

We are using jquery.validate.js for client side validation of forms and processing. Download this file from the link given at the end of this article and place this file inside your js folder of active theme.

Also Create a file called ajax-auth-script.js and place it inside your js folder of active theme as well.

Handling the AJAX Request

On the basis of data received we have to notify the user that login/registration was successful and perform the login or just notify him that his data is incorrect.

First I created a new folder libs inside theme folder and then created file custom-ajax-auth.php with all of these code below and saved file inside libs folder. I will call this file in functions.php for server side processing.

Open functions.php file of your theme and place the line there:

Function ajax_auth_init()

We have registered and enqueued necessary CSS and JS file here and created a JS object called ajax_auth_object and enable the users with no privileges (not logged in) to call our functions as well.

The wp_ajax_nopriv_ajaxlogin WordPress hook is important part to note. If you leave out “nopriv” and use wp_ajax_ajaxlogin then only users that are logged in can access the functions.

Rest of the functions are self explanatory. They collect the data received from POST method, check if the nonce is valid and then tries to perform user register and/or login with the received data.

Congratulations! You have nice looking AJAX login and register forms now, powered with jQuery validation. You can perform WordPress AJAX Login and Register without a Plugin now.

Update (January 12, 2015): I have written a post to add Forgot Password with AJAX functionality in code & steps mentioned here. Have a look over that tutorial too and download improved files there after reading this post.

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

  • misad91

    How to redirect user to another page if login is successful?

    • Amit Sonkhiya

      Misad,

      Under the Handling the AJAX Request section, change home_url() with home_url(‘/PageName/’) for redirecturl (line number #14)

      • misad91

        thanks

      • GiuseppeTr

        Can I redirect user to another page for only register form?

        • Amit Sonkhiya

          You can change id of link that opens register popup and specify href attribute to desired page

          <a href="”>Logout

          Login

          Signup

          • GiuseppeTr

            Thanks !

        • Amit Sonkhiya

          Or if you just wish to redirect newly registered user to another page then modify line number #14 to:

          ‘redirecturl’ => isset($_POST[’email’]) ? ‘YOUR_ANOTHER_URL’ : home_url(),

          • GiuseppeTr

            good

  • misad91

    I have problem with login. I was include file that contain login form in widget and form doesn’t show only white screen on click

    • Amit Sonkhiya

      misad, you should put only login & signup buttons in widget (the code block below ‘We also need login and signup buttons….’).

      Rest of the processes are same, keep the forms in ajax-auth.php file under your active theme otherwise forms won’t show as script would be unable to locate the file.

      • Amit Sonkhiya

        My apologies as I didn’t explicitly clear in my post.

        There is a “jquery.validate.js” file also included in the zip. Upload this file also on the js folder in your active theme (same where you uploaded ajax-auth-script.js) as it’s also required for AJAX processing.

  • amritanshu kalia

    hi Amit ,
    thanks for the tutorial.
    i have a problem that when i submitt the for i.e registration /login , i keep getting the following error :

    The requested URL /login was not found on this server.

    Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request

    • Amit Sonkhiya

      Amrit,

      My apologies as I didn’t explicitly clear in my post.

      There is a “jquery.validate.js” file also included in the zip. Upload this file also on the js folder in your active theme as it’s also required for AJAX processing.

      Meanwhile I’m updating the post.

      • Faham Shaikh

        Hi Amit,

        I am having the jquery validate but I am still getting 404

        • Amit Sonkhiya

          I suggest you to mention the steps you followed for ajax login or provide url where you are facing issue. You can use http://fellowtuts.com/contact/ if you wish to remain private.

          • Faham Shaikh

            Hello Amit,

            For some reason my reply was not posted… anyways.

            I differed a bit from the steps and the steps that I followed were:

            1) Copy form code in header
            2) Add functions in functions.php
            3) Create JS file named ajax-login.js and change the filename in functions.php
            4) Add jQuery validate js
            5) Create css file and place it in appropriate location

            All the files are being found but I doubt that the validation function is working. I say so because when I tried to receive an alert when the validation worked and also when the validation fails but the alert box did not came up.

          • Amit Sonkhiya

            I tried to check url you provided but url was not accessible. I would suggest you to try code same as I explained instead of making changes at first go. Also if you are using any plugin for the same, then please deactivate them first.

            Validation may not work if jquey fail to call the function. Having found is not enough. Let me check them until if I could access.

          • Faham Shaikh

            Hello Amit,

            Please do not worry anymore because I was able to resolve the problem. As I suspected the validation jQuery was not being called and hence all the trouble. I had to enqueque validate.js in head and the authorization scripts in footer in order for this to work.

            Thank you very much for your support.

            Regards
            Faham

          • Amit Sonkhiya

            Glad to hear that you have sorted out the problem.

    • Amit Sonkhiya

      Still if you are unable to resolve the issue then please give me the link to your website.

  • Developer

    Thank you

  • Devaeti

    Great! Thank you very much!

  • Hi Amit,

    Thank you very much for the tutorial.

    I see that it doesn’t log me in rather it says: “Sending user info, please wait…”

    Please help.

    I followed all the steps mentioned.

    • Hi Amit,
      I got it to work, but the dashboard panel on the top doesn’t show up immediately after loggin in. But I had to refresh multiple times to show the “Logout” button and WordPress dashboard panel.

      What can be done for this? Please help.

      • Are you using any wordpress caching plugin. If yes, please clear the cache first. If you still have issue then Please tell us your website url where you have implemented this so that we can check here and let you know the solution.

    • Sukeshni

      Hi Vinod,
      I am getting the same problem.
      Please help.

      • Amit Sonkhiya

        Hello,
        This error occurs if there is some issue in processing functions in custom-ajax-auth.php. Please provide your site link.

        • Sukeshni

          Hi Amit,
          Thank you for the post.
          I am trying it on localhost for learning purpose.
          That issue is resolved . But now the login/register form credentials (i.e username and password) in the form are not assigned properly, defaultly blank value is passed.

          • Amit Sonkhiya

            Hi, how did you determine that? The form won’t submit with empty values or until client validation passes. Please ensure you don’t have another form/input elements with same id.

            You can also check values being submitted via putting alert(‘input: ‘ + username + ‘, ‘ +password) in ajax-auth-script.js after line #40

            Also you can modify function ajax_login in custom-ajax-auth.php to check what is function actually receiving by modifying it:

            function ajax_login () {
            $input = ‘Username: ‘.$_POST[‘username’].’ Password: ‘.$_POST[‘password’];

            echo json_encode(array(‘loggedin’=>false, ‘message’=>__($input)));

            die();
            }

            Also ensure you are not using other plugin to achieve the same. Please check them and let me know.

  • Sandi

    Hi Amit,

    Very thank you for the tutorial.
    how to create forget password form?

    Thanks!
    Sandi

  • Amit Sonkhiya

    Vinod,

    There is zM Ajax Login & Register plugin install there which is causing the issue. Please remove that one first.

  • Dannie Herdyawan

    Hi, thanks for great tutorial… I created this tutorial and using with my site http://www.ciusan.com… Can I create a plugin with this tutorial and upload them in to a wordpress plugin?

    Regards,
    Dannie Herdyawan

    • Amit Sonkhiya

      Hi,
      Glad to know that you are using it beautifully in your site.
      Can you please give a credit as back-link to this tutorial from your plugin page in WP plugin repository if you are intended to develop as plugin 🙂

    • Dannie Herdyawan

      Hai, this the link: https://wordpress.org/plugins/ciusan-register-login/
      But, i want to ask, i want if succesfull login redirect to http://www.ciusan.com/profile, and if new registered redirect to thanks page.. How??? Thanks…

      • Amit Sonkhiya

        Hi Dannie,

        Good job & thanks for the credit. Here is the little tweak.
        In custom-ajax-auth.php change line #14
        ‘redirecturl’ => home_url()
        to
        ‘redirecturl’ => isset($_POST[‘email’]) ? ‘YOUR_THANKS_URL’ : home_url(‘/profile/’)

        • Dannie Herdyawan

          Yeah, thanks….. 😀

        • Dannie Herdyawan

          Hmm, wait… can i change from ‘redirecturl’ => isset($_POST[‘email’]) ? ‘YOUR_THANKS_URL’ : home_url(‘/profile/’) to ‘redirecturl’ => isset($_POST[‘email’]) ? ‘YOUR_THANKS_URL’ : ‘OTHER_URL’

          • Amit Sonkhiya

            Yup! you can change it to wherever you wish to redirect the user.

          • Dannie Herdyawan

            Hi, i created this

            ‘redirecturl’ => isset($_POST[’emai’]) ? $options[‘register_redirect_URL’] : $options[‘login_redirect_URL’],

            If the login is successful, the redirect is correct, but if new register redirect to same with login.. I do not know why?

          • Amit Sonkhiya

            Dannie, I have updated my previous reply and added one more variable there. Please check that and let me know.

          • Mahu

            Is it also possible to redirect the user to the page which he last viewed?

          • Amit Sonkhiya

            Hi Mahu,

            You can change line #65 in ajax-auth-script.js to

            document.location.href = document.URL;

            To return at page where you have provided account credentials in popup form.

            Correct me if I have misunderstood last viewed page.

          • Mahu

            That is exactly what i wanted to achieve. Works perfect, thank you very much.

          • Dannie.. you can change this line in your ajax-auth-script.js file :

            document.location.href = $(this).attr (‘id’) == ‘register’ ? ajax_auth_object.register_redirect : ajax_auth_object.redirecturl;

            replace it with –

            document.location.href = $(ctrl).attr (‘id’) == ‘register’ ? ajax_auth_object.register_redirect : ajax_auth_object.redirecturl;

          • Dannie Herdyawan

            Cool, it’s work..

            Thank you very much K K Agrawa….
            Thanks also to you Amit Sonkhiya, who has made this tutorial…

        • Dannie Herdyawan

          Sorry, still not working ….. Or I must to send the file, and you check it?

  • Mahu

    Hello Amit,

    Thank you very much for this awesome tutorial. Unfortunately it doesnt work well for me. I did everything exactly as described, but when i click on the login oder register button the website only refreshes. I also get this error: “Uncaught TypeError: undefined is not a function” in Line 3 of ajax-auth-script.js, which is:

    $(‘#pop_login, #pop_signup’).live(‘click’, function (e) {

    Any ideas how to get it working? I would love to use it on my site.

    Thank you so much,
    Mahu

    • Amit Sonkhiya

      I suspect there is any jQuery related issue stuck with your site. Will you please provide the link to your page?

      • Mahu

        Thank you so much for your fast reply, the homepage is: http://184990.webhosting29.1blu.de/sportsbuddies/
        It is still under construction.
        The two links are on the left side of the page, just above the blue box.

        Since i tried to install this Ajax Plugin also the Masonry Plugin (http://184990.webhosting29.1blu.de/sportsbuddies/) is broken.

        Best regards,
        Mahu

      • Mahu

        You were right, it was a rquery conflict. Got it fixed. Thank you again.

        • Amit Sonkhiya

          Great! You have fixed that.

        • César

          Bro, I’m experiencing exactly the same issue. How did you fix it on your end? Thanks in advance.

  • MadMathilda

    Hi Amit,

    I tried to implement google reCAPTCHA, I have registered our Site so I have the secret+site key, and the captcha is displayed at the SignUp page, as I wanted.
    The problem ist, how do I verify the reCAPCTHA? In the custom-ajax-auth.php?
    (I tried that but it didn’t work, it would be perfect if you include it in your tutorial) Because SignUp is still possible even if the user doesn’t even try the captcha.

    PS: Thanks for the great tutorial 🙂

    Best Regards,
    Mathilda

    • Amit Sonkhiya

      Hi,

      Please check this article (http://fellowtuts.com/php/google-new-recaptcha-using-php-are-you-a-robot/) and try to make a few modifications as listed:

      ===============
      In ajax-auth-script.js change line #43 – 49

      if ($(this).attr(‘id’) == ‘register’) {
      action = ‘ajaxregister’;
      username = $(‘#signonname’).val();
      password = $(‘#signonpassword’).val();
      email = $(‘#email’).val();
      security = $(‘#signonsecurity’).val();
      }

      To

      recaptcha= ”;
      if ($(this).attr(‘id’) == ‘register’) {
      action = ‘ajaxregister’;
      username = $(‘#signonname’).val();
      password = $(‘#signonpassword’).val();
      email = $(‘#email’).val();
      security = $(‘#signonsecurity’).val();
      recaptcha = $(‘#g-recaptcha-response’).val();
      }
      ===============

      In ajax-auth-script.js change line #55 – 60

      data: {
      ‘action’: action,
      ‘username’: username,
      ‘password’: password,
      ’email’: email,
      ‘security’: security

      To

      data: {
      ‘action’: action,
      ‘username’: username,
      ‘password’: password,
      ’email’: email,
      ‘security’: security,
      ‘recaptcha’: recaptcha
      ===============

      In custom-ajax-auth.php after

      check_ajax_referer( ‘ajax-register-nonce’, ‘security’ );

      function (line #44) add the following code:

      $recaptcha=$_POST[‘recaptcha’];
      if(!empty($recaptcha))
      {
      $google_url=”https://www.google.com/recaptcha/api/siteverify”;
      $secret=’GOOGLE SECRET KEY’;
      $ip=$_SERVER[‘REMOTE_ADDR’];
      $url=$google_url.”?secret=”.$secret.”&response=”.$recaptcha.”&remoteip=”.$ip;
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($curl, CURLOPT_TIMEOUT, 10);
      curl_setopt($curl, CURLOPT_USERAGENT, “Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16”);
      $results = curl_exec($curl);
      curl_close($curl);
      $res= json_decode($results, true);
      if(!$res[‘success’])
      {
      echo json_encode(array(‘loggedin’=>false, ‘message’=>__(‘reCAPTCHA invalid’)));
      die();
      }
      }
      else
      {
      echo json_encode(array(‘loggedin’=>false, ‘message’=>__(‘Please enter reCAPTCHA’)));
      die();
      }
      ===============

      Please note that I didn’t test the code still I hope it will sure help you and this code is for reCAPTCHA 2.0 If you face any issue then please provide the page URL.

      Also thanks for the suggestion, we will try to provide the same as soon.

      • MadMathilda

        Hi Amit,

        thank you so much for that great guide. Recaptcha does now work very well!

        The only bug i experienced so far is: When i try to register and solve the captcha properly but use an email-adress or username which is already used (error: This username is already registered.) then change the username/email to another one and try to submit, it always outputs “reCAPTCHA invalid”. I think this is because you cant submit the same recaptcha twice, so there must be a way to make the user solve the recaptcha again (the recaptcha form must reset) if the username or email is already used. Any ideas on how to fix that?

        The Homepage is: http://www.sportsbuddies.de/ the register-link is on the top left (“Registrieren”).

        Again, thank you so much for your help and keep up the good work! This blog is awesome!

        Best regards,
        Mathilda

        PS: Is there any way to donate you for a cup of coffee? 🙂

        • Amit Sonkhiya

          Hi

          Change line #62 in ajax-auth-script.js

          success: function (data) {

          To

          success: function (data) {
          grecaptcha.reset();

          Do this little modification and let me know.

          Also thanks for your kindness and appreciation. Please check your email account (from: support@fellowtuts.com) for the same.

          Regard,
          Amit Sonkhiya

          • MadMathilda

            Hi,

            the solution worked like a charm. Now everything works like it should, thank you so much!
            Your email just arrived as well.

            Best regards,
            Mathilda

          • Tomáš Halo

            Hello Mathilda,

            i found that you implemet terms of use into registration form in your website http://www.sportsbuddies.de/ (Ich habe die Datenschutzrichtlinien und… )

            Can you help me how to do it right way?

            Thanks for your help

          • MadMathilda

            Sorry for the late answer, i was away a while.
            Yes, just put in the following line where you wish your checkbox in the ajax-auth.php file:
            YOUR TEXT HERE

            I think that was all. Hope it works

          • ChrisBrowndog

            Hi Amit,

            Love the tutorial, and I’ve implemented it perfectly so far on one of the websites I am developing. As MadMathilda has mentioned, I’m trying to implement the new google reCaptcha on the registration form, however I cannot manage to get this to work. I’ve followed the tutorial on the link that you posted to her, however that doesn’t appear to be for Ajax submissions and as a result I’m slightly lost.

            Any assistance you could provide here would be very helpful.

            Many thanks,

            Chris

          • Amit Sonkhiya

            Hi Chris,

            We are testing the AJAX login with reCaptcha script & hope will post new ready to implement article very soon.

          • Tomáš Halo

            Hello Chris,

            look at the code of this plugin (https://wordpress.org/plugins/ciusan-register-login/) – it is based on this tutorial and is also implement google recaptcha as well.

          • Amit Sonkhiya
  • Adam

    Thanks for the nice tutorial 🙂

    I have though one big problem: when I try to login (from the overlayed login form) I just get redirected to the build-in wp-login.php …

    What could be the problem ?

    Cheers,
    Adam

    • Amit Sonkhiya

      Hi,

      There is some jQuery conflict in your page and if you are using any other plugin for AJAX login then first remove that. Also check if the button click event is being fired or not using

      $(‘form#login, form#register’).on(‘submit’, function (e) {

      alert (‘Button Fired’);

      in ajax-auth script.js line number #35

      • Adam

        Hi Amit,

        First of all, the button is fired.

        Secondly I have deactivated and deleted a plugin which also were a ajax login.

        To overcome I have set a variable $j to run in noConflict mode:

        $j = jQuery.noConflict();

        $j(document).ready(function ($) {

        … that does not solved the issue 🙁

        /Adam

        • Amit Sonkhiya

          Hi,

          ajax_auth_object renders by php code in custom-ajax-auth.php. please ensure that you have properly included the file in functions.php and is correct.

          If this doesn’t help you then please provide a link to page.

          • Adam

            I have now solved the not-defined ajax_auth_object issue and the validator issue…

            But when trying to log in in nothing happens after the status message “Sending user info, please wait…” appears :/

            Cheers,
            Adam

          • Amit Sonkhiya

            Hi

            There is some issue with php script in the file at your end and it’s unable to return the response..

      • Adam

        just after submission I found an error: in ajax-auth-script.js in line #111 ‘Uncaught TypeError: undefined is not a function – I had a typo on embeding jquery.validate… unfortunately that wasn’t the error causing the problem…

      • Adam

        Ok, two new ‘undefined’:

        ajax_auth_object is not defined in ajax-auth-script.js line #51 ( $(‘p.status’, this).show().text(ajax_auth_object.loadingmessage);)
        and
        ‘Cannot read property ‘settings’ of undefined’ in jquery.validate.js line #348
        (settings = validator.settings;)

        Why is these beautiful scripts not working ? #justasking

        Cheers,
        Adam

  • Tomáš Halo

    Hello,
    this is one of the most usefull tutorial i have ever read. Thanks a lot.
    Amit, i have a small question about implementation a function to registration form. Do you find it interesting for you for a small donation? More info via e-mail (info@tomashalo.com).

    Tomas

    • Amit Sonkhiya

      Hi,

      Thanks for appreciation and support. We would be glad to implement the function as you wish. Let me know what is desired!

      Thanks

      • Tomáš Halo

        Hello,
        explanation: i have function which you can select role in registration form. (you can choose register as subscriber or contributor). It works fine in standart wordpress registration form. but i would like to know how to implement it into your ajax registration.

        Thanks!

        • Amit Sonkhiya

          Hi Tomas,

          My reply will arrive in your inbox in a few minutes.

          Thank you.

          • Claudio Sabatinelli

            Hi Amit,
            can you send me the same solution?

            Thanks!

          • Amit Sonkhiya

            Hi,
            I have sent you an email.

            Thanks.

  • lawless99

    Beautiful tutorial – I have successfully implemented this in my site management plugin. Thank you very much Amit!

  • Work Rajo

    Hi,

    How can I proceed to use ajax login/register with buddypress?
    What changes should I make?
    Thanks

    • Amit Sonkhiya

      Hi,

      As the question is not directly related to post still to integrate it with BuddyPress you are requested to use our troubleshooting services (http://fellowtuts.com/troubleshooting/)

  • MadMathilda

    Hello Amit,

    is there any way to improve the registration form in a Double Opt-in process? So that the user receives a validation key (maybe just the same random key as from the forgot password form) which he has to enter to fulfill the registration?
    In that way the user verifies his Email.
    Or is this only possible using the random wordpress registration form?

    Best Regards,
    Mathilda 🙂

    • Hello MadMathilda,
      Yes, we can do it by sending an email to user with new randomly generated password which will be used for first time login by the user.

      After inserting user in wp, we can shoot an email to the user. I think this will help you to get the point.

    • Amit Sonkhiya

      Hi MadMathilda,

      Welcome back!
      I just dropped you an email regarding the solution.

      Thanks

      • robin

        Hi Amit, can you please mail me the same code which is responsible for email verification on registration.
        my email id : onilledigital.robin@gmail.com

        • Amit Sonkhiya

          Hi,

          Please check gmail from support@fellowtuts.com

          • rex

            Hi Amit,

            first of all, thanks for this very userfull plugin.

            please email me the solution for this too.. (user receives a verification Email to fulfill the registration)
            also, i want users to log in using either email OR username that they used while registration.

            cm.rex.darkangel@gmail.com

            Thanks ^_^

          • Amit Sonkhiya

            Hi Rex

            I have sent you an email from support@fellowtuts.com

          • Farhan Kureshi

            Hi Amit, can you please send me the same code for email verification on registration.?
            my email id : farhankureshi71@gmail.com

      • nmfifi

        Hi Amit, thank you for your tutorial. this is very helpfull.. can you please send me the same code for email verification on registration.? thanks before.

  • Aaron

    Hello, i reached the step to insert require_once( get_template_directory() . ‘/libs/custom-ajax-auth.php’ ); into the functions.php. I recieved an error

    Warning:
    require_once(/hermes/bosnaweb04a/b2721/ipg.ghanarecipecom/wp-content/themes/inspirythemes-food-recipes/libs/custom-ajax-auth.php):
    failed to open stream: No such file or directory in
    /hermes/bosnaweb04a/b2721/ipg.ghanarecipecom/wp-content/themes/inspirythemes-food-recipes-child/functions.php
    on line 18

    Fatal error: require_once(): Failed opening required
    ‘/hermes/bosnaweb04a/b2721/ipg.ghanarecipecom/wp-content/themes/inspirythemes-food-recipes/libs/custom-ajax-auth.php’
    (include_path=’.:/usr/local/lib/php-5.3.13/lib/php’) in
    /hermes/bosnaweb04a/b2721/ipg.ghanarecipecom/wp-content/themes/inspirythemes-food-recipes-child/functions.php
    on line 18

    I need help. 🙁

    • Hello Aaron,

      I think you forgot to place the custom-ajax-auth.php file in lib directory of the them. Please check once. If not found there, download from here and place it in lib directory of your current theme.

    • Amit Sonkhiya

      Hi,

      As you mentioned, I can sense that you are using child theme and you have placed file in parent theme. Please try with shifting file to child and also validate that necessary js/css files can be loaded by inspecting path in browser’s source code.

      https://codex.wordpress.org/Function_Reference/get_template_directory

      • Aaron

        Hmm. Have a look at my functions.php file code>>

        ** and I placed the file in the correct path.

        • Aaron
        • Aaron

          /* custom PHP functions below this line */
          function ajaxloginlogout_scripts() {
          wp_register_script( ‘jquery.validate’, get_stylesheet_directory_uri() . ‘/js/jquery.validate.js’, array() , false, true );
          wp_register_script( ‘ajax-auth-script’, get_stylesheet_directory_uri() . ‘/js/ajax-auth-script.js’, array() , false, true );
          wp_enqueue_script( ‘jquery.validate’ );
          wp_enqueue_script( ‘ajax-auth-script’ );
          }
          add_action( ‘wp_enqueue_scripts’, ‘ajaxloginlogout_scripts’, 99 );

  • Kirill

    HI Amit,
    I have got a problem with your tutorial. After the last step (adding code to function.php) my website is turning to white screen.

    • Amit Sonkhiya

      Hi,

      It’s not due to the code we provided, I suspect that you have some line breaks or empty space either at the end or begining of your functions.php

  • Sharaz Hossein

    I followed the steps exactly but the form shows up on the page. I thought when I click on the button it will do a popup. Do I need to have a popup plugin and call fhe ajax-auth.php in it?

    • Amit Sonkhiya

      You don’t need any external plugin. You are missing ajax-auth-script.js which performs pop-up. Inspect page html on browser and ensure that this file is there & accessible.

  • Sharaz Hossein

    Scratch my first comment. I didn’t check to see if the files were loading. When using a child theme you have to use get_bloginfo( ‘stylesheet_directory’ ) to get the child theme path.

    That issue is fixed and form works, however, it gets stuck at “Sending user info, please wait…” If I wait for about 30 seconds and refresh it shows me that I am logged in. It’s not redirecting on it’s own. Any ideas?

    • Amit Sonkhiya

      There might be two reasons:
      Either whole code in libs/custom-ajax-auth.php is not included in your functions.php or any another ajax login plugin (if you are using) might cause the problem.

      Provide us url of the page where you have implemented the login buttons.

      • Sharaz Hossein

        Thanks for the quick response Amit, I appreciate it. This is a great approach to login and very well done.

        I don’t have any other login plugin active. The libs/custom-ajax-auth.php is loaded in the functions.php. if I test with the wrong password the Ajax returns wrong password message. I changed the message to make sure it’s coming back from the ajax call. When the password is correct, it sits there and does not redirect. If I refresh the screen manually it shows that I am logged in.

        I try to test for an alert in jQuery if it’s loggedin but nothing happens…

        Can I send you an email with my production link?

        • Amit Sonkhiya

          Sure. We would try our best.

  • Vaishali Bansal

    Hi Amit,
    Its a wonderful tutorial. I am new to wordpress. I am not getting login or signup link on my page when m logging out.
    But when i log in again, the same page showing me the logout link.
    Can you please help.

    Thanks
    Vaishali

    • Amit Sonkhiya

      Hi,

      Did you place the login/out links as described at http://fellowtuts.com/wordpress/wordpress-ajax-login-and-register-without-a-plugin/#crayon-554363385a325416370194-0

      What is url of page where you have implemented the buttons?

      • Vaishali Bansal

        I have created a page and pasted below code in it.


        <a href="”>Logout

        Login
        Signup

        I hope I’ve done it correctly.:(

        Please correct me if I am wrong.

        • Amit Sonkhiya

          Did you place that above code directly at WordPress post editor under dashboard for that page? And php blocks are missing.

          If you did so then you did absolutely wrong. You need to go into theme files using FTP and place that code at appropriate location normally header.php in your active theme.

          Like we added code inside functions.php require_once( get_template_directory() . ‘/libs/custom-ajax-auth.php’ );

          • Vaishali Bansal

            I created a custom function in functions.php.
            Then created shortcode for that and pasted that shortcode in the page created in dashboard.

            And then I gave link to that page in menu.

            I am doing all this at localhost

          • Amit Sonkhiya

            I would like to suggest you to direct paste above code to header.php or anywhere else just to check if it works?

          • Vaishali Bansal

            It’s not working.:( Something is going wrong in else block. M able to see logout link.

            I printed ‘hello’ message in else block. Hello is displayed but login and register button are not displayed.

            Not able to conclude,whats going wrong.

          • Amit Sonkhiya

            Leave everything else. You should try printing separate messages in if else block and use two different browsers. Caching feature might cause you to face the issue so can try with clearing cookies. Also never go to dashboard while testing all this.

        • cmurphy

          Amit
          great tutorial it works good, I was wondering if it is possible to ad more fields to the registration form? like full name, last name and zip code

          thanks

          • Amit Sonkhiya

            For this you have to:
            Add form fields in form (ajax-auth.php).
            Modify code for form validation & submission in js as well as
            Server side ajax_register function to accept added fields & insert into DB.

            If you feel it difficult to implement then you can write us at http://fellowtuts.com/troubleshooting/

  • Mickael Lambert

    This is awesome, it works perfectly for me, really nice work!!

    I just have a question, have you already try to add social medias login / register ?

    Beautiful work!

    • Amit Sonkhiya

      Hi,

      Thanks for appreciation. We didn’t attempt to integrate social login into this. Do you need one?

      • Mickael Lambert

        You’re welcome.

        Yes, i have no idea how to do it, but i’ll try in the week!

  • Mohit

    Hi Amit this is an excellent post can u tell me how can i integrate this with a plugin

    • Amit Sonkhiya

      You can download & modify that plugin with integrating our code. Knowledge of PHP & WP are required. If you it tough you can use our service: http://fellowtuts.com/troubleshooting/

  • Md Al Amin

    This what I’m looking for. You are the man. Thanks. I bookmarked the site. Hope you’ll post more article I need 🙂

  • David Duong

    Hi Amit,

    Thank you so much about great tutorial. It is working on
    my website. When I install a website to sub folder in my server, the
    login form are working, but it doesnt show the admin bar and change
    login link to logout link. When I use it on the root, it’s working very
    well. You can help me?

    Thanks

    David

    • Amit Sonkhiya

      Hi David,

      When you use sub-directory, your theme’s css & js path get change. To handle the issue, change all occurrence of get_template_directory_uri() with get_stylesheet_directory_uri() in your custom-ajax-auth.php file, save, check & let me know.

      Also you can check if js & css files are included properly by inspecting browser code.

      Thanks

  • Ha Lam Truong

    We try it http://www.fashionedits.com/blog2/, but register form is showed and the layout is terrible.

  • Javid Rad

    hi amit,
    thank you for tutorial
    how can add dispaly_name field on register form?
    i’m whant user can write display_name on register form

    thank u so much 😉

    • Amit Sonkhiya

      Hi,

      This involves many steps to perform carefully. I’m describing them in short:

      Create an input field in register form (ajax-auth.php)
      Style the input in (ajax-auth-style.css)
      Validate & pass display_name input value on form submit with AJAX in (ajax-auth-script.js)
      Accept the input on ajax_register function in info array in (custom-ajax-auth.php)

      Give it a try and still if you face any issue then we would like to help you out.

  • MadMax

    Hi Amit,

    thx for this nice tutorial, but I have a problem to expand this script. How can I integrate the “get_template_part” in the ”
    is_user_logged_in” part? For example I add an other form to you script, called “example”. It works well, but not in the “is_user_logged_in” part – why?

    This way works:

    <a href="”>Logout

    Login
    Example

    This way doesnt work:

    <a href="”>Logout
    Example

    Login

    Can you help me?

    • MadMax

      What, where is my code? I hope this post will show it ….

      This way works:
      “”
      “<a href="”>Logout”
      “”
      Login
      Example
      “”

      This way doesnt work:
      “”
      “<a href="”>Logout”
      Example
      “”
      Login
      “”

      • Amit Sonkhiya

        Hello MadMax,

        Our comment form can read html in your comment and renders as link if present.

        The script provided here doesn’t load if the user is already logged in because ajax_auth_init() function (see in custom-ajax-auth.php) who is responsible to render css & script, is being called only for not logged in user.

        To load the example script I suggest you to separate the script and load it using wp_register_script() & wp_enqueue_script() functions as we did in custom-ajax-auth.php along with get_template_part() in

        <?php if (is_user_logged_in()) { ?>
        //logout url

        //example url

        <?php } else { get_template_part(‘ajax’, ‘auth’); ?>
        //login url

        //register url
        <?php } ?>

        Still if you wish to integrate it within code provide here, you can write us: http://fellowtuts.com/troubleshooting/

        • MadMax

          Hello Amit,

          thx for support! I´ve sent you a mail, you´ve got it? Hope you can help me for this modification?

          • Amit Sonkhiya

            Hi,

            I have already sent you code almost 15 hours ago from support@fellowtuts.com address.

            I’m sending you the same again from a gmail address. Please check back.

          • MadMax

            Ouh, ok, maybe my mailbox fails. I send you a new email adress. Big thx!

          • Amit Sonkhiya

            Did you get now? Check your spam folder as well.

          • MadMax

            Sry for late reply – yes, I´ve got it – big thx!! Awesome support here!

          • adebowalepro

            Please how do I contact you for a private chat on some BuddyPress issues.

          • Amit Sonkhiya

            Hi,
            you can drop us a mail at support@fellowtuts.com along with Skype Id and some detail about the issue first.

  • sonia

    Hi Amit

    I am going to implement a register, lost password and login functionality with your code. Just wondering if you could answer MadMathilda’s question for me to i.e.

    is there any way to improve the registration form in a Double Opt-in process? So that the user receives a verification Email to fulfill the registration?
    Or is this only possible using the random wordpress registration form?

    I am big on security. I would gladly donate if the solution works for me.

    • Amit Sonkhiya

      Hi,

      I have sent to an email regarding solution from support@fellowtuts.com hours ago. Please check the same (spam folder as well).

      Thanks

  • Sanjeev Kumar

    I love your way for implimenting this but in my local its not working
    when i click on login or signup page get refreshed.
    I want this in my website please give me solution to this problem

    • Amit Sonkhiya

      You should first check if are all necessary resources (css, js files) are included properly by inspecting browser source code of your page.

      If you still face issues, you can upload your project to test server and write us at http://fellowtuts.com/troubleshooting/

      • Sanjeev Kumar

        I am confused how to check where is the error

        • Amit Sonkhiya

          I have sent you an email from support@fellowtuts.com. Please check your emails including spam folder as well.

          Thanks

  • Jignesh Huskerit

    Hello, Amit

    I want to do In login and Register how to remove Username and set Email as username
    It is possible in your code ?

    • Jignesh Huskerit

      please ans it

      • Amit Sonkhiya

        Inside ajax_login/ajax_register function you can validate & process if user input is an email using WordPress is_email() & email_exists() functions.

        In login form you can alter username input to <input id=”username” type=”text” class=”required email” name=”username”>

        In register form remove username field and it’s reference in ajax-auth-script.js and custom-ajax-auth.php by inspecting & altering code carefully.

  • What’s up to every one, the contents present at this web site are truly amazing for people knowledge, well, keep up the good work fellows.

  • Dawid Adach

    Hi Amit!,

    Great work!

    I have a question – is there a possibility to trigger modal from more than 1 place in the page?

    When I tried to paste the same code twice I got my modal displayed however it doesn’t work anymore. When you try login it always gives “Wrong username or password” and when you try to register it says that login field is empty although it isnt…

    Any idea?

    • Amit Sonkhiya

      Hi,
      You don’t need to place the same code twice except the login/register buttons.

      Just place the second code block (6 lines of code ABOVE Styling the box in this article). wherever you wish to place to trigger modal from more than 1 place.

  • Kevin De Guzman

    I have a problem with this, when i logged in admin account it will redirect, but if i logged in normal user account it will stuck into sending information and when i reload the page it is already logged in

  • Kevin De Guzman

    I have a problem with this, when i logged in using admin account it will redirected, but if i logged in using normal user account it will stuck into sending information and when i reload the page it is already logged in

    • Amit Sonkhiya

      Hi, The issue is that you are not getting ajax response from server. Are you using any other plugin for ajax login as well? Then please remove that first.

  • Anuradha Sharma

    I want when user register they got conformation email after that they can login … Can you let me know what change i can do on the code so that this functionality work..I don’t want its auto login after registration

    • Amit Sonkhiya

      Hi,

      You do need to make many steps to obtain so as listed below:

      1. On server side script under register function send email to user using wp_mail() function.

      2. in js, instead of redirecting user, show the message to check email.

      3. Create function to validate email when user clicks on the link he/she receives in email

      If you would like us to do this for you then please contact us at http://fellowtuts.com/troubleshooting/

  • CopyLoop

    Every time I try to add this code:

    require_once( get_template_directory() . ‘/libs/custom-ajax-auth.php’ );

    to my functions.php file, I get a server error. I am using a child theme and I am trying to add the code to the functions.php file in the parent theme.

    What am I doing wrong?

    • Amit Sonkhiya

      Hi CopyLoop

      In your current case, your libs folder should exist in parent theme. You can also test using child theme by using get_stylesheet_directory().

      I would be able to help you more if you can tell me what server errors are you facing. You can email us at support@fellowtuts.com

      Thanks

      • CopyLoop

        Amit:
        I created the libs folder in my parent theme directory and uploaded the custom-ajax-auth.php file. I then pasted the line of php code into my functions.php file (in the parent theme), and I’m getting the following error message:

        Not Acceptable! As appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.

        I’m wondering if all of the additional files from your tutorial — css, php, and js — should go into the respective folders in the parent theme. I’ll wait to hear from you before making any changes, though.

        Here’s a link to my site so you can see for yourself: http://www.hellinabucket.com/

        • ashok pawar

          If you are using child theme then create libs folder in child theme directory and upload custom-ajax-auth.php file.
          1. change “get_template_directory_uri()” to “get_stylesheet_directory_uri()”.

          2. move “if condition” inside “function ajax_auth_init()”

          function ajax_auth_init(){
          // complete code
          if ( ! is_user_logged_in() ) {
          add_action(‘init’, ‘ajax_auth_init’);
          }
          }

          It worked for me…

  • is there an easy way to modify this so that each individual field is checked via ajax call when the user moves focus to another field?

    btw thanks for the great write up

    • Amit Sonkhiya

      Hi @PropProphet X

      Thanks for appreciation and asking. As far as I can remember jQuery itself checks fields as soon as control looses focus here.

      To be honest there is no easy way to modify what you wish because in this case you would need to play with both client side as server side code. ajax-auth-script.js and custom-ajax-auth.php

      If you wish to achieve the same, you can contact us at http://fellowtuts.com/troubleshooting/ as well

      Thanks

  • Kashif Munir

    Thanks for the awesome tutorial. 5 stars…

  • Harry

    Hi Amit,

    Absolutely amazing tutorial. I have noticed that you have also done the tutorial with password recover and reCAPTCHA, my question is, which of the tutorials has the most up to date code?

    I am looking to have all login, register, password recover and reCAPTCHA.

    Would it be best to download the reCAPTCHA zip and code in the recover password using the tutorial or visa versa?

    All the Best,

    Harry

    • Amit Sonkhiya

      Hello Harry
      Thanks for the appreciation. The reCAPTCHA tutorial has most up to date code and I would suggest you to integrate Forget Password code into reCAPTCHA tutorial’s code. If you face any issue then feel free to ask us.

      • Harry

        Thank you so much Amit,

        Such a fantastic lightweight code, rather than using a plugin.

        One last question if I may, I have created some new user meta fields for my wordpress site e.g. “address”, “business name” etc, how would I implement these new fields in the user registration form?

        Any guidance would be greatly appreciated.

        • Amit Sonkhiya

          Hello Harry,

          You have to perform 3 steps:

          1. Add custom input box in form (ajax-auth.php)

          2. validate and submit form (ajax-auth-script.js)

          3. On register function in custom-ajax-auth.php, add records to database using WP user meta functions

  • Farhan Kureshi

    Hi Amit, can you please send me the same code for email verification on registration.?
    my email id : farhankureshi71@gmail.com

    • Amit Sonkhiya

      Hello Farhan,

      I have dropped you an email to afford-said address. Pleas check that

      Thanks

  • Tom

    How would one go about converting this into a plugin ?

    • Amit Sonkhiya

      There are already plugins based on this tutorials

  • bobin56

    Hi Amit ,
    Please help me here , i don’t want to log in the user after he has register , so my question is how do i just display a message like “Thank you for registering , we will let you know when your account is approved ” , in which i will approve the user later . Thanks again 🙂

    • Amit Sonkhiya

      Hi,

      You would need to implement a list of tasks for that:

      Upon registration set a user meta key to flag user as unapproved
      Send email to admin for new user registration.
      On approval send email to user
      Change custom-ajax-auth.php to adopt them.

      If you just wish to send the message to user you can change line #64 in custom-ajax-auth.php

      auth_user_login($info[‘nickname’], $info[‘user_pass’], ‘Registration’);

      with

      echo json_encode(array(‘loggedin’=>false, ‘message’=>__(‘Your account will be approved soon.’)));

      Or write us at support@fellowtuts.com for a full implementation

      • bobin56

        Thanks Amit , this is very helpful info , appreciate 🙂

  • Dawid Adach

    Hi Amit,

    I am having issue with the script. When I try to register/login I process stops at “Sending user info, please wait…” message. I have included jQuery with below script inside functions.php

    function my_scripts_method() {

    wp_deregister_script( ‘jquery’ );
    wp_register_script( ‘jquery’, ‘http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js’);
    wp_enqueue_script( ‘jquery’ );

    }

    add_action(‘wp_enqueue_scripts’, ‘my_scripts_method’);

    • Amit Sonkhiya

      Hi Dawid,

      Is there any url to check the functionality?

  • Dilip Agrawal

    Hi,
    This is too better, I always use this..

  • zanderh1

    Hello Amit,

    I am having an issue, were I cannot go to the backend when I log in with this form. When I click any button on the black admin bar it redirects me to 404 not found, and when I log in with the normal wordpress login everything is okay. Any ideas why this is not working?

    • zanderh1

      I finally figured it out. I added to wp_signon($info , true) instead of false because I am using a secure server and that fixed everything. Also the reason it was redirecting me, had to do with iThemes Security.

      • Amit Sonkhiya

        Glad you have rectified this.

  • bobin56

    Hi Amit , i am running a bit of a problem here , i got a double registration , looks like wp_insert_user runs twice and i can’t see where i got it wrong .

    function ajax_register_player(){

    // First check the nonce, if it fails the function will break

    check_ajax_referer( ‘player-register-nonce’, ‘security’ );

    // Nonce is checked, get the POST data and sign user on

    $info = array();

    $info[‘user_nicename’] = $info[‘nickname’] = $info[‘display_name’]= $info[‘user_login’] = sanitize_user($_POST[‘username’]) ;

    $info[‘phone’] = sanitize_text_field($_POST[‘phone’]);

    $info[‘user_email’] = sanitize_email( $_POST[’email’]);

    $info[‘role’]=$_POST[‘role’];//”basketballer”; // //

    $info[‘first_name’]=sanitize_text_field($_POST[‘first_name’]);

    // Register the user

    $playerinfo=wp_insert_user($info);

    if ( is_wp_error($playerinfo) )
    {
    $error =$playerinfo->get_error_codes() ;
    if(in_array(’empty_user_login’, $error))
    {
    echo json_encode(array(‘loggedin’=>false, ‘message’=>__($playerinfo->get_error_message(’empty_user_login’))));
    }
    elseif(in_array(‘existing_user_login’,$error))
    {
    echo json_encode(array(‘loggedin’=>false, ‘message’=>__(‘This username is already registered.’)));
    }
    elseif(in_array(‘existing_user_email’,$error))
    {
    echo json_encode(array(‘loggedin’=>false, ‘message’=>__(‘This email address is already registered.’)));
    }
    } else
    {
    echo json_encode(array(‘loggedin’=>false, ‘message’=>__(‘Thanks for Signing Up . Your account will be approved soon.’)));
    }
    die();
    }

    • Amit Sonkhiya

      Hi Bobin

      The code you provided is just registration process script. It doesn’t show how is this function called. I would need full code to have a look. You can write us to support@fellowtuts.com

      • bobin56

        Solved it , i had saved another file that was doing the same thing. Thanks again.

  • Fall In LoVe

    i have error after send data. Redirect http://www.???.az//register

    • Amit Sonkhiya

      Hi Fall
      what is your site url. I think you are pointing to some site with restrict keywords. Drop us email with this information at support@fellowtuts.com

  • Anahit Aida Ghazaryan

    Hi,

    Thank you for good tutorial.

    I have one question.

    I wanna send user notifcation after he Sign UP to his email but did not find how i could do that? Where i need to implement my code within custom-ajax-auth.php which function?

    Thanks in advance.

    • Amit Sonkhiya

      Hi Anahit,

      The email sending code should be placed inside ajax_register() function just before auth_user_login() call

      Thanks

  • Anahit Aida Ghazaryan

    Hi,

    Thank you for the good tutorial.

    One question please?

    How i can send notification email to user after registration to his email?

    Thanks in advance.

    • Amit Sonkhiya

      Hi,

      You can use wp_mail function inside ajax_register() function

      Thanks

  • Anahit Ghazaryan

    Hi,

    Thank you for the cool tutorial.

    I have one question.

    How i can have the First Name and Last Name added to registration form please?

    Thanks in advance.

    • Amit Sonkhiya

      HI,

      You need to add more text input fields in the form, validate them and process in server side php file. The $info array then would contain all required information.

      If you wish us to perform the same for you then write us at support@fellowtuts.com

      Thanks

      • Anahit Ghazaryan

        I had created the fields, validation and the process to be added to server side but when i try to display it within wordpress cureent user function like this

        user_login . “n”; ?>
        user_email . “n”;?>
        user_level . “n”;?>
        user_firstname . “n”;?>
        user_lastname . “n”;?>
        display_name . “n”;?>
        ID . “n”;?>

        It did not display the Firstname and Surname properly. Do i need to add some extra code for this?

        I also need to create edit function within the webpage so user could edit the fields.

        Could you help me with the info please?

        Thanks in advance.

      • Anahit Ghazaryan

        Here is the code for displaying wordpress user info. it was corrupted within my previous reply.

        user_login . “n”; ?>

        user_email . “n”;?>

        user_level . “n”;?>

        user_firstname . “n”;?>

        user_lastname . “n”;?>

        display_name . “n”;?>

        ID . “n”;?>

      • Anahit Ghazaryan

        Seems code did not displayed properly within my reply. I used the same code from here https://codex.wordpress.org/Function_Reference/get_currentuserinfo .So you could see the code there.

        Thanks in advance.

        • Amit Sonkhiya

          It all depends on how are you coding? There might be some error in your code.

          Write us at support@fellowtuts.com if you wish us to correct it.

          Thanks

          • Anahit Ghazaryan

            I had created them like this

            $info[‘user_firstname’] = $_POST[‘firstname’];
            $info[‘user_surname’] = $_POST[‘surname’];

            Also i noticed that for the email and password you are using something different

            $info[‘user_email’] = sanitize_email( $_POST[’email’]);

            For what is sanitize_email ? Maybe that’s why mine added info did not recognized by wordpress?

  • Anahit Ghazaryan

    One other question please.

    I am trying to send an email notification to new registered user but did not know where exactly i need to do that? Within which function? I tried to do it within ajax_register() function but seems did not work.

    Thanks in advance.

    • Amit Sonkhiya

      Hi Anahit,

      The email sending code should be placed inside ajax_register() function just before auth_user_login() call

      Thanks

      • Anahit Ghazaryan

        Yes thank you very much for the swift response. One more question please. I wanna display some message when email is sent like this $mail = wp_mail( $to, $subject, $message1, $headers ); if( $mail )
        $success = ‘Check your inbox.’; But it did not work. I guess that the wrong thing is the variable $success. Could you help me to figure out?

        Thanks in advance.

        • Amit Sonkhiya

          For your need, call auth_user_login() in $mail condition and modify the message on line #82 accordingly.

          Be careful to deal if mail doesn’t go, in my opinion it would better to modify the message without using if($mail condition)

          • Anahit Ghazaryan

            ok so i need to show a message like check your inbox so i need to show something when email received and don’t know where to write that in which variable so it will show that in the place of this message – Sending user info, please wait…

            Thanks in advance.

  • pradip

    hello,

    Really thanks for your article. it works perfect for me. hope you will create more useful tutorials like this.

    thanks again.

  • Ilia

    Hey Amit,
    Great tutorial, I have one noob question… How do you add Login/Log out and register buttons to the main menu?
    Let me know!

    Thanks

    • Amit Sonkhiya

      Hi Llia,

      It’s quite tricky. You have to add them dynamically to the menu (example: http://www.wpbeginner.com/wp-themes/how-to-add-custom-items-to-specific-wordpress-menus/) and change the selector ids with your menu ids in ajax-auth-script.js (line #35) to fire the click event.

      If you face any issue or wish us to do so for you, please write us at support@fellowtuts.com

      • Ruby

        Hey Amit,
        Great tutorial, I have one noob question… How do you add Login/Log out and register buttons to the main menu?
        Let me know!

        pls give me a clear answer.. I am eagerly waiting for you..

        Thanks

  • Anahit Ghazaryan

    I followed the steps and only the register form is not working. it is leading to /register. How this can happen? Am i missing anything?

    Thanks in advance.

    • Amit Sonkhiya

      Hello Anahit,

      Please provide url of page where you are facing the issue. I can reply only after checking that

      • Anahit Ghazaryan

        hey thanks for the feedback. I figured out to solve my issue. I have another question re the Register form. In your example you are creating the account confirmation email step which is not safe. So my question is if i wanna add confirmation step and then create the account how the code will look like if (is_wp_error($user_register) ){

        $error = $user_register->get_error_codes();

        if(in_array(’empty_user_login’, $error))

        echo json_encode(array(‘loggedin’=>false, ‘message’=>__($user_register->get_error_message(’empty_user_login’))));

        elseif(in_array(‘existing_user_login’,$error))

        echo json_encode(array(‘loggedin’=>false, ‘message’=>__(‘Already used‘),’usedusername’=>’yes’, ‘usedemail’=>’no’));

        elseif(in_array(‘existing_user_email’,$error))

        echo json_encode(array(‘loggedin’=>false, ‘message’=>__(‘Already used‘),’usedusername’=>’no’, ‘usedemail’=>’yes’));

        }

        Thanks in advance!

        • Anahit Ghazaryan

          How i can just check if there is a user with that email or username but do not insert the info as how i see with $user_register = wp_insert_user($info) we are inserting the info when no errors so how i could do that same check without inserting user account automatically and do that after confirmation email step?

          Thanks in advance.

          • Amit Sonkhiya

            Use email_exists() and username_exists() functions provided by WordPress

          • Anahit Ghazaryan

            Yes thank you very much!

          • Anahit Ghazaryan

            Hey I just created the confirmation step process before adding and activating the account and stacked with the following issue – how i can store User First Name and Last Name in _usermeta table for the corresponding user? Per the confirmation step am keeping another db table for pending users and when they are going to with activation link am just adding that same info to wp_users table.

            Thanks in advance.

          • Anahit Ghazaryan

            Any ideas?

          • Amit Sonkhiya

            Use add_user_meta() and get_user_meta() functions built into WP for the same

          • Anahit Ghazaryan

            But how?

          • Amit Sonkhiya

            Hi Anahit,

            Sorry for late reply. It’s impossible to answer your query in 3-4 simple lines. You would need some expertise over WP & PHP to obtain the same. If you are finding it difficult to implement, please write us to support@fellowtuts.com

            Thanks

  • Dawid Adach

    Amit,
    It seems that this script uses some obsolete functions like live() which are not in newest jQuery.

    Currently WordPress uses jquery version 1.12.3 including jQuery migrate which is not recommended. If you try to get rid of it:

    function remove_jquery_migrate( &$scripts)

    {

    if(!is_admin())

    {

    $scripts->remove( ‘jquery’);

    $scripts->add( ‘jquery’, false, array( ‘jquery-core’ ), ‘1.12.3’ );

    }

    }

    ?>

    You script stops working. Could you please update it using new function on() ?

    Thanks!

  • Awesome! Thanks you, Amit for this great tutorial.

  • John William

    Great & Helpful Tutorial. So easy to understand and use, Thanks for sharing with us.
    I have also created another Ajax Login Form Using jQuery and PHP.

  • Abhishek Gupta

    Hi I don’t know how to link this to my Sql. Please explain that code also so that it will work for me.

  • Nicolas

    Hi Amit,

    Thank you for this great tutorial.

    I am trying to put the files in a plugin but I have two issues:
    1) this one has already been commented, the login form get stucked at “Sending user info, please wait…”
    2) I added this code in my plugin index page:

    add_action( ‘init’, ‘cxxlf_include_scripts’ );

    function cxxlf_include_scripts() {

    include( ‘libs/custom-ajax-auth.php’ );
    include( ‘ajax-auth.php’ );

    // CSS
    wp_enqueue_style( ‘Style Ajax Login Form’, plugin_dir_url( __FILE__ ) . ‘css/ajax-auth-style.css’ );
    }

    But I have the error message headers already sent by (… /ajax-auth.php:6)

    Do you know how can I sort those two errors?

    Than you for your help.
    Nicolas.

    • Amit Sonkhiya

      Hi Nicolas.

      I think that you have solved the issues and edited the comment later. Glad to know that.

      Thanks

  • yeo

    Hi, how do I set up this login / register ajax to show at the click of a button in my navigation menu?

    • Amit Sonkhiya

      Hi yeo,

      You can either rename selectors show_login, show_signup with Id’s of your those navigation menus in ajax-auth-script.js (line #25) or if you are comfortable with dynamically menus creation in WP then you can add navigation menu buttons to popup login/register forms. If you wish us to implement the same then write us to support@fellowtuts.com

    • Amit Sonkhiya

      Hi

      Please check your email from support@fellowtuts.com

      Thanks

  • Atul Suroshe

    Hi Amit,
    Instead of placing buttons, can we auto populate modal box for login? If yes how to do that?

  • Александр Перминов

    Hello, tell me please why when i push the login button he send me to /wp-admin page ?
    Error: ajax-auth-script.js?ver=4.6.1:74 Uncaught TypeError: jQuery(…).validate is not a function
    Thnx

    • lujain

      i have the same problem can you tell how did you solve it ?

      • Ubby

        The author mixes $() and jQuery() in his script – bad coding.

        In ‘ajax-auth-script.js’ go down to ‘Client side form validation’ and replace jQuery() by $().

  • Александр Перминов

    Hello,
    I have a problem. When i push the button login, he do all well. But when i try to go wp-admin, he send me to login form again. And i have error: Uncaught TypeError: Cannot read property ‘settings’ of undefined jquery.validate.js?ver=4.6.1:345
    Help please. Thnx.

  • Jasmin Abenojar Moran
  • Furkan Khan

    hey can you plz tell me how that work. and i did everything as said in that blog. but its not working.

    • Amit Sonkhiya

      Hello Furkan,

      To understand how it works, you would need to know WordPress (mostly), jQuery and PHP.

      Saying not working won’t help us to rectify the issue. Please mention exact problem and link to your page if you can provide.

      Thanks

  • Roobiya E. Roobiya E

    Hey Amit,
    Great tutorial, I have one noob question… How do you add Login/Log out and register buttons to the main menu?
    Let me know!

    Thanks

    • Amit Sonkhiya

      Hi Roobiya

      We perform the same through dynamically registering menu items via code in WordPress.

      Thanks

  • Sajib Roy

    Thanks for your great work, would you please tell me how to redirect buddpress user profile page after login ?

    I did something like this under (custom-ajax-auth.php) ::

    global $current_user;

    wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'loadingmessage' => __('Sending user info, please wait...'),
    'redirecturl' => home_url().'/members/'.$current_user->display_name
    ));

    • Amit Sonkhiya

      Hi Sajib,

      The code block is executed when it page is loaded initially and that time the user is not logged in yet. To redirect to profile page, you would need to pass this url after login as json response in auth_user_login function and modify js a bit to perform redirection.

      If you would like us to implement that same for you, please write us at support@fellowtuts.com

  • Dave Garcia

    Hi, I copied all the files as you had mentioned. I created a login page and added to menu location. Not sure how to call the function on my theme? I’m new to wordpress. Please advice.

    • Amit Sonkhiya

      Hi dave,

      If you are using this in menu, you need add this menu item dynamically via code

  • Sudhir Singh

    Hi,

    How can redirect according to roles

    • Amit Sonkhiya

      Hi Sudhir,

      Please read comments on this blog post, I have mentioned it here a few times

  • lujain

    Hi Amit ,
    i did the same coding as you said, and there are no pulgins activated for login/registration form…. nothing works even when i press login it takes me to login to wordpress account as an admin if i am signed out, and takes me to logout page if i logged in to wordpress !
    Please Help

    • Amit Sonkhiya

      Hi lujain,

      I’m unable to assist you until I don’t have link to your page facing issue. Please provide us the url. If you wish to remain private, mail to support@fellowtuts.com

  • lujain

    Hello Amit ,
    i debugged my website and an error said :

    JQuerry is not a function in ajax-auth-script.js file !

    I need help, note that i removed the popups because i dont need them ,

    • lujain

      ajax-auth-script.js?ver=4.6.1:77 Uncaught TypeError: jQuery(…).validate is not a function

      • lujain

        I just solved it thanks !

  • lujain

    Hello Amit, where should i include the ajax-auth-script.js ??

  • Thanks for article, great blog. Thanks!

  • jay

    hello amit,

    Given code is not working in my fresh wordoress setup in my local system.

    Can you please help me. I am using given step.

    Step 1) I have create file ajax-auth.php
    and put “AJAX Login and Register Forms” given code as per instruciton .

    Step 2) create ajax-auth-style.css file inside css folder and past css code.

    Step 3) Get jquery.validate.js cdn and put header.php file.

    Step 4) Create ajax-auth-script.js file inside js folder and past given js code.

    Step 5) Create custom-ajax-auth.php file inside libs folder and set path

    require_once( get_template_directory() . ‘/libs/custom-ajax-auth.php’ ); in function.php

    • Amit Sonkhiya

      Hello Jay

      The steps you followed seem alright and I can’t assist you in a local system. If you have a live link available, let me know

      Thanks

  • Davor

    Hi.. After I update the wordpress to new version 4.7.5 this code not work any more… I think there is some issues with import user data when register.. and login now from some reason redirect to wp-logn.php … and register form stop on “Sending user info, please wait…”

    Can you please see what is issues with code.. I can not find it.. tnx

    • Amit Sonkhiya

      Hello Davor,

      We will check the code & update if we find any such issue. Meanwhile, you can send us link to your website to let us check

      Thanks

      • Davor

        Hi Amit .. Registration is closed for now on live site.. because its client site… I try in local and get same issues … I am not sure what is error.. but will try again…

      • Davor

        I tested again.. and actually code work with new wordpress also.. somebody changed code in ajax-auth-script.js file and this was the issues.. sorry for false alarm 🙂

  • Ghulam Waheed

    Hi Amit,
    I have followed your tutorial very carefully for my website to show Login and Register tabs on the header so that users could login and register them self however The tabs have been created on the top left but when I click it doesn’t show anything pop windows to login or register. As soon as I click It blurs the entire home page and nothing happens. I’m at budding stage as a “Web Application Developer”, I might have done something wrong while following up your tutorial. One more question is that I’m unable to upload the Zip files on WordPress you have mentioned at the bottom of your blog. Kindly help me with your reply immediately please.

    • Amit Sonkhiya

      Hello Ghulam,

      After WordPress update, we will check our code. Meanwhile you can send us link to your WP website to let us review

      • Ghulam Waheed

        Hi Amit,
        Thank you so much for your quick respond. I’ll appreciate if you kindly go through my website and review it. it’s http://www.ordersfood.com
        we’r still developing this website. The Login and Signup tabs have been created on the left side on homepage header. Please review and provide me the solution.

        • Amit Sonkhiya

          Hi Ghulam,

          Sorry as I couldn’t notice your comment. Is that issue resolved?

  • ngp

    I follow your code. When I click login/register in the form, it redirects to wp-login.

  • Moe Lalati

    Hello Amit, i’ve done everything but the link of css and js to the main page doesn’t seem to work ;l i’m getting nothing!

    wp_register_style( ‘ajax-auth-style’, get_template_directory_uri() . ‘/css/ajax-auth-style.css’ );
    wp_enqueue_style(‘ajax-auth-style’);

    wp_register_script(‘validate-script’, get_template_directory_uri() . ‘/js/jquery.validate.js’, array(‘jquery’) );
    wp_enqueue_script(‘validate-script’);

    wp_register_script(‘ajax-auth-script’, get_template_directory_uri() . ‘/js/ajax-auth-script.js’, array(‘jquery’) );
    wp_enqueue_script(‘ajax-auth-script’);

    the css file is in the css folder, the two js files and in the js folder, when inspecting source , no js or css errors given.
    Tried changing theme from twelveseventeen to 16 still the same, oh and ofc i’ve added the line in functions.php

    • Amit Sonkhiya

      Hello Moe,
      Here is a list you must check:
      — Can you see script/style tag added in browser code related to aforesaid CSS/JS
      — Are you calling action to enqueue? add_action( ‘wp_enqueue_scripts’, ‘YOUR FUNCTION’);
      — If using a child theme use get_stylesheet_directory_uri() instead of get_template_directory_uri() and use correct path then

  • babarharoon1234

    hi amit i have done the same thing and follow as you say but in result i got both popup does n show up

    both login / signup link appear but when i click on any one boom the form display right down there i have shere the picture i want popup as yours please help me i love ajax alot thanks for giving this such a lesson for ajax lover

    • Amit Sonkhiya

      hello @disqus_gkOfxqykfU:disqus
      Please share us a link to your page where you have implemented login/signup links

  • babarharoon1234

    amit thank you soo very much for your quick reply i am glad and appreciate for this
    dear amite i solve that issue that was my fault during implementation
    Amit i love your work and way of tutorial i am not much develpor just a student but i love ajax i was searching the same thing that you have done !
    dear amit please create a new one tutorial for ajax lover totally ajaxify theme like animated page, post, comment, user register , category and tags custom post type , etc using of ajax magic i know it is soo hard but i saw your post and tutorials that all are awesome …
    you can do this by video tutorials or by articals
    it is just a request as a beginner thanks you again for reply
    beautiful work
    and please share your demos please

    • Amit Sonkhiya

      Hello @disqus_gkOfxqykfU:disqus

      Thanks for the appreciation and telling your interests & seek. Currently we are busy in changing theme & introducing new features to Fellow Tuts blog. We will also include our work and demos. Be assured we will update you regarding Ajax content as we publish.

      Until meanwhile you can get all Ajax related posts here through the link: http://fellowtuts.com/?s=ajax

  • Vysakh Gopalakrishnan

    hii how can i create a forgot password popup in this

  • Sarath Chandran

    hii amit , i want to change color when error message is shown,how can i change

    • Amit Sonkhiya

      Hello @disqus_i4vcRJRgdC:disqus
      You can use either addClass() if you have defined class with that color or inline styling using JS. Tweak around line #63 – #66 in ajax-auth-script.js

  • Sarath Chandran

    hii amit can u help me to create a custom profile page for update user information?