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 the 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

WordPress AJAX Login and Register without a Plugin

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 the active theme.

Also, Create a file called ajax-auth-script.js and place it inside your js folder of the 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 the file inside libs folder. I will call this file in functions.php for server-side processing.

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

Note about the parent/child theme: If you’re implementing the AJAX Login and Register feature in a child theme then replace all 3 occurrences of get_template_directory_uri() function with get_stylesheet_directory_uri() in custom-ajax-auth.php (Line #3, #6 and #9).

Similarly change get_template_directory() function with get_stylesheet_directory() inside require_once(). However, replacing these function in a parent theme won’t affect the working in any manner. But implementation in a child theme must need these replacements.

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 an 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 the 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

338 COMMENTS

  1. noreenbroun453 says:

    I think this is among the most significant information for me. And i’m glad reading your article. But want to remark on some general things, The web site style is ideal, the articles is really excellent : D. Good job, cheers

    Reply
  2. Anya Venable says:

    Oh my goodness! Impressive article dude! Many thanks, However I am encountering issues with your RSS. I don’t understand why I cannot join it. Is there anybody getting similar RSS issues? Anyone who knows the answer can you kindly respond? Thanks!!

    Reply
  3. Nell Carnegie says:

    I do consider all of the ideas you have offered on your post. They’re really convincing and can definitely work. Still, the posts are very short for newbies. May you please prolong them a bit from subsequent time? Thank you for the post.

    Reply
    1. Amit Sonkhiya says:

      Hi,

      Thank you for your honest words. Altho, these posts are for intermediate developers, I will try to write posts for beginners as well.

      Reply
  4. Tim says:

    Hi Amit, and thank you very much for this awesome guide!

    Among all articles & snippets related to AJAX login for WordPress, the only yours work properly.

    Some notices from me:

    I put scripts in Theme Child Directory, and in my case I also had to modify require_once function like:


    require_once( 'libs/custom-ajax-auth.php' );

    Otherwise I got “failed to open stream” error when trying to use require_once with get_template_directory() or get_stylesheet_directory_uri().

    Also, I have Gravity Forms Registration Add-on, and use your solution to make Gravity Forms Login Form Widget work with AJAX. Since there is no embedded AJAX feature for that form, but I want to put it in Popup window.

    To achieve it, I just modified ajax-auth-script.js, by replacing: form#login with form#gform_0 everywhere.

    And two following strings as well, with correct widget’s input #id :


    username = $('form#gform_0 #input_1').val();
    password = $('form#gform_0 #input_2').val();

    Reply
    1. Tim says:

      Would be appreciate for any suggestion from your side, to fix one small issue.

      When I put incorrect username / password to login form and press button, I got a message that information is not correct. So on this stage AJAX works properly.

      But after that, button do not response anymore when clicking 2nd, 3rd … times.

      In browser’s Inspection tab -> Network, there are no requests when clicking button again.

      What is the problem could it be?

      Thank you

      Reply
      1. Amit Sonkhiya says:

        Hello Tim

        The WordPress function get_stylesheet_directory_uri() shouldn’t be used inside require_once() because it returns URL, not a path. The correct line that should work is:

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

        Regarding failure upon subsequent button triggers: I won’t be able to help until I could have the page URL. Do let me know the link to the page where the form is placed.

        Reply
    1. Amit Sonkhiya says:

      @kaisbo:disqus

      The code doesn’t create two users twice. You might have one additional plugin installed to create user.

      Reply
  5. Florian Meeuwsen says:

    Thank you so much for this awesome tutorial! I implemented it exactly as described and it works… most of the time. I would say that one in three times it doesn’t actually log in and it just closes and goes back to the page, even though the account info is correct, then when I do the exact same thing next time it works. Do you have any idea what could be the issue?

    PS: I am running this locally for now with Flywheel

    Reply
    1. Amit Sonkhiya says:

      While without a link to the page it’s quite hard to assist. Still other things you can do are:

      If you’re using any caching plugin then try disabling it.
      Remove any other plugin for AJAX login.

      Inspect the element in the browser console for the AJAX call.

      Reply
  6. Shariful Sabuj says:

    hi amit,
    I follow these steps but there is no change in my site.

    Login form is not shown anywhere.
    Please help me.

    -Shariful.

    Reply
      1. Shariful Sabuj says:

        I just followed your tutorial steps but not implemented in any page.
        I’m new in development. so would you please more clearly explain so that any non technical people can develop login page?

        Reply
        1. Amit Sonkhiya says:

          @shariful_sabuj:disqus

          This solutions doesn’t create any separate login/register page. It shows the form in a popup when you click to the buttons. Further, the code to add those buttons is also given in this tutorial (2nd code snippet of 5 lines here from the beginning.

          <a href="”>Logout

          Login
          Signup

          You have to add these buttons somewhere in your website like in the header. Once these links/buttons are shown, click to either and the form will popup if you have done the rest things properly.

          Sadly, you need to have intermediate knowledge of WordPress to implement these. If you’re facing trouble, write me at amit@astech.solutions so that I can guide you properly.

          Reply
    1. Amit Sonkhiya says:

      hello @Mihajlo

      WordPress assigns the role specified in Settings -> New User Default Role, during new user registration. So just set it there. Other options are set_role() and wp_update_user() as well as $info[‘role’] => ‘subscriber’ in ajax_register() function here. Use either one.

      Reply
  7. serqan says:

    Hi Amit, thank you so much.

    It’s like there’s a big problem.

    While the member registration is closed, the member is still registering.

    Do you have a solution to this problem?

    I’d appreciate it.

    Reply
    1. Amit Sonkhiya says:

      Hello @disqus_7SDvhLmAGp:disqus
      There are many customization available as per how do you want to disable the registration from. Among many, you can return the following response in the ajax_register() function

      echo json_encode(array(‘loggedin’=>false, ‘message’=>__(‘Registration is currently disable.’)));

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

      However if you want to completely hide the form then you need a lot customization.

      Reply
      1. serqan says:

        I want to hide the form along with an “if else” when member registration is closed. Is this possible? I would be very grateful if you could help me.

        Reply
        1. Amit Sonkhiya says:

          Hello @disqus_7SDvhLmAGp:disqus

          Unfortunately, there is no few lines of code with current implementation to hide the registration at this moment.

          However, I can suggest you the following steps to perform:

          1. Show the registration form markup.only if registration is enabled.
          2. Perform the same to the registration form link.
          3. Edit the JS and check if the registration form exist before firing any event.
          4. Put the registration code in registration enabled condition.

          If you are unable to do the customization, you can either write me at amit@astech.solutions or request us on this page:

          https://www.astech.solutions/services/wordpress-development-themes-plugins/

          Do let me hear back.

          Reply
      1. You’re welcome. It’s pleasing to hear it. But there is a problem here. When I make the above mentioned change (security to signonsecurity), it gives an error of ajax 403 (Forbidden). What do you think about this?

        Reply
        1. Amit Sonkhiya says:

          Oh LOL! Lmao, man I forgot what I have written in the jQuery part.

          The previous code was correct. The security parameter in PHP is not the nonce field, it’s the POST parameter containing the correct nonce value during AJAX request.

          Check the line number 42 and 48 in ajax-auth-script.js. So use ‘security’, it is correct parameter to pass else nonce validation will fail.

          Reply
  8. Logan Carlile says:

    Hello I am having an issue where the ajax login form allows me to login, sort of. If I set the redirect to the homepage after login it sends me to the homepage and gives me the admin bar at the top. However if I try to then go to the admin dashboard it asks me to login again with the normal wordpress login.

    I inspected what was going on and it appears when I try to go to the dashboard it removes the wordpress login cookie and wants me to reauth for some reasons instead of just taking me to the dashboard.

    Curious if you have ran into this issue or if you know what could be causing this issue or how to resolve it?

    Reply
    1. Amit Sonkhiya says:

      @logan_carlile:disqus

      This issue has come into my notice few days ago and I suspect that it is appearing since version 4.9 of WordPress. I haven’t checked the cause yet, hope will get it soon.

      Reply
          1. Amit Sonkhiya says:

            @l@logan_carlile:disqus @@ofyalcin:disqus

            Check the line no #77 In custom-ajax-auth.php. Try the login by replacing

            $user_signon = wp_signon( $info, false );
            with
            $user_signon = wp_signon( $info, ” );

            Means try login with changing the second parameter in the wp_signon() call to ” (empty string without space). It should work. In case it fails then set the parameter to true and recheck.

          2. Hi Amit, thank you!

            Yes it is working well. Bu if SSL is not enabled on the site, wouldn’t it be a problem? And another problem. The user is redirected to the homepage after login, but the admin bar does not appear until you refresh the page.

          3. Amit Sonkhiya says:

            @ofyalcin:disqus

            When you leave the second parameter empty, WordPress automatically determines if secured cookies should be used or not. In past this parameter had false as default value, now the empty string.

            The browser loads the cached page, I have to check how to force it to fetch the fresh page from the server. Also, a caching plugin installed might also cause the trouble.

  9. Milan says:

    Hi Amit,

    I am trying to use this snippet on my website for login and registration popup function but its not functioning proper. Its not what forming a popup instead its something looking that its a separate field in the header as I want the login or register button at the header. website link https://shopaxio.com if you can help me any way, also if you can give me a combined snippet for forget password with the login and register feature.

    Milan

    Reply
      1. Milan says:

        Hi Amit,
        Thank you for response, I have made changes where I have the put CSS and JS file in the parent theme’s folder since I am using a child theme so now I am able to reproduce the button and the pop up functionality. But you can see I am still facing problem in the JS part where there is some error in the jequery validating part can you suggest why it is so and if please also provide me the solution.

        Reply
        1. Amit Sonkhiya says:

          Hello Milan,

          Since you’re using a child theme, do all these implementations in your child theme.

          Then, replace all three occurrences of get_template_directory_uri() with get_stylesheet_directory_uri() in custom-ajax-auth.php.

          Also, replace get_template_directory() function with get_stylesheet_directory() in require_once() function call.

          Additionally, you have missed properly enqueuing jquery.validate.js that’s why the validation part is failing. I can see that the file isn’t loading. Put the file in the js folder and your problem will fix.

          Regarding Forget password implementation, the updated zip and steps are provided in the article:
          https://fellowtuts.com/wordpress/forgot-password-with-ajax-in-wordpress-login-and-register/

          Do let me know if anything else is needed.

          Reply
          1. Milan says:

            Hi Amit,

            Thanks a lot for your help and the snippet. It’s working great but only I need to know one thing more is there any way to display the my account function over there after the user logged in to the website. Actually I am using it for my ecommerce website where the customer need to view the order details and other account related things.

          2. Amit Sonkhiya says:

            You need to place a link to Account page in PHP script inside is_user_logged_in() code block. Add the given line before wp_logout_url( home_url() ) link:

            Also, I see that the website needs few customization in theme files and settings to work better for both, users and search engines. You can write at amit@astech.club or use given link for further discussion:

            https://www.astech.club/services/e-commerce-solutions/

          3. Milan says:

            Hi Amit,
            Sorry for saying you thanks so late. Thanks a lot to u again, your suggestions worked and it’s working fine. I have an another query can you suggest some snippets for multi-step checkout process, where in while customer press proceed for checkout then he get the field as step 1 for entering mobile/email for login or register if new user then on filling get the password field for new customer additional step before password OTP verification then the 2nd step billing or shipping if shipping is different then 3rd step order review and last & 4th step payment mode selection with credit card/debit card/internet banking/emi details entering field or else COD.
            Regards
            Milan

          4. Amit Sonkhiya says:

            I don’t think there would be one single script to satisfy all your needs. Further, I think you’re using WooCommerce plugin. You can check, implement and test various scripts for the sake of 2F authentication. Search Google for “woocommerce sms based authentication”.

            WC already have good interface to handle billing and payment processes withing admin panel as you asked. We’ve done with that. All you need is, understand it and enable desired features. Additionally, you might need to buy/install extra add-ones for more payment gateways. You can also customize behavior with hooks provided in WC.

            If you need very dedicated or personalized solution, I would suggest you not to consume extensive time and take the help of professional developers like us. You can contact us at https://www.astech.club or write at amit@astech.club

  10. Shabu james says:

    Is there any way to stay in the page where we logged in without redirecting to homepage ? ‘redirecturl’ => home_url(), Currently it was redirecting to homepage. I am using this login in a popup. Is there any way to stay in current page

    Reply
    1. Amit Sonkhiya says:

      @shabujames:disqus

      That’s is indeed possible but required more complicated code along with AJAX. The Login link here in the navigation menu to this website works in the same manner.

      You need either AJAX or redirection because there is need to update cookies, username and login/logout links.

      Reply
        1. Amit Sonkhiya says:

          Change the line #65 in ajax-auth-script.js. Remove document.location.href = ajax_auth_object.redirecturl; and add location.reload(true);

          Also, ensure that the browser loads the updated JS file then, as they cache resources

          Reply
          1. Amit Sonkhiya says:

            It’s weird. Provide both URLs (before and after reload) via strictly copying them from browser address bar. You can try either of these code as well:

            window.location.reload(true);
            location.href = location.href;
            document.location.href = location.href;

            If nothing works, try the implementation on a remote server.

    1. Amit Sonkhiya says:

      Hello @nuno_sarmento:disqus

      I’m having trouble in location the page. Please ensure that the URL is correct or provide me a correct one

      Reply
    1. Amit Sonkhiya says:

      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

      Reply
  11. babarharoon1234 says:

    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

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
  12. babarharoon1234 says:

    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

    Reply
    1. Amit Sonkhiya says:

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

      Reply
  13. Moe Lalati says:

    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

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
  14. Ghulam Waheed says:

    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.

    Reply
    1. Amit Sonkhiya says:

      Hello Ghulam,

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

      Reply
      1. Ghulam Waheed says:

        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.

        Reply
  15. Davor says:

    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

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
      1. Davor says:

        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…

        Reply
      2. Davor says:

        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 🙂

        Reply
  16. jay says:

    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

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
  17. lujain says:

    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 ,

    Reply
  18. lujain says:

    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

    Reply
  19. Dave Garcia says:

    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.

    Reply
  20. Sajib Roy says:

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

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
  21. Roobiya E. Roobiya E says:

    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

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
  22. Jasmin Abenojar Moran says:
    Reply
  23. Александр Перминов says:

    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.

    Reply
  24. Александр Перминов says:

    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

    Reply
      1. Ubby says:

        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 $().

        Reply
    1. Amit Sonkhiya says:

      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

      Reply
  25. Nicolas says:

    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.

    Reply
  26. Abhishek Gupta says:

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

    Reply
  27. Dawid Adach says:

    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!

    Reply
  28. Anahit Ghazaryan says:

    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.

    Reply
      1. Anahit Ghazaryan says:

        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!

        Reply
        1. Anahit Ghazaryan says:

          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.

          Reply
          1. Anahit Ghazaryan says:

            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.

          2. Amit Sonkhiya says:

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

          3. Amit Sonkhiya says:

            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

  29. Ilia says:

    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

    Reply
      1. Ruby says:

        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

        Reply
  30. pradip says:

    hello,

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

    thanks again.

    Reply
  31. Anahit Ghazaryan says:

    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.

    Reply
    1. Amit Sonkhiya says:

      Hi Anahit,

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

      Thanks

      Reply
      1. Anahit Ghazaryan says:

        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.

        Reply
        1. Amit Sonkhiya says:

          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)

          Reply
          1. Anahit Ghazaryan says:

            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.

  32. Anahit Ghazaryan says:

    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.

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
      1. Anahit Ghazaryan says:

        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.

        Reply
      2. Anahit Ghazaryan says:

        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”;?>

        Reply
          1. Anahit Ghazaryan says:

            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?

  33. Anahit Aida Ghazaryan says:

    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.

    Reply
  34. Anahit Aida Ghazaryan says:

    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.

    Reply
    1. Amit Sonkhiya says:

      Hi Anahit,

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

      Thanks

      Reply
  35. bobin56 says:

    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();
    }

    Reply
  36. zanderh1 says:

    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?

    Reply
    1. zanderh1 says:

      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.

      Reply
  37. Dawid Adach says:

    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’);

    Reply
  38. bobin56 says:

    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 🙂

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
  39. Harry says:

    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

    Reply
    1. Amit Sonkhiya says:

      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.

      Reply
      1. Harry says:

        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.

        Reply
        1. Amit Sonkhiya says:

          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

          Reply
    1. Amit Sonkhiya says:

      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

      Reply
  40. CopyLoop says:

    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?

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
      1. CopyLoop says:

        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/

        Reply
        1. ashok pawar says:

          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…

          Reply
  41. Anuradha Sharma says:

    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

    Reply
    1. Amit Sonkhiya says:

      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/

      Reply
  42. Kevin De Guzman says:

    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

    Reply
    1. Amit Sonkhiya says:

      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.

      Reply
  43. Kevin De Guzman says:

    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

    Reply
  44. Dawid Adach says:

    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?

    Reply
    1. Amit Sonkhiya says:

      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.

      Reply
  45. Jignesh Huskerit says:

    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 ?

    Reply
      1. Amit Sonkhiya says:

        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.

        Reply
        1. reX says:

          i tried it. but im not able to get it done :'(
          specially the part “validate & process if user input is an email using WordPress is_email() & email_exists() functions.”

          Reply
  46. Sanjeev Kumar says:

    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

    Reply
  47. sonia says:

    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.

    Reply
  48. MadMax says:

    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?

    Reply
    1. MadMax says:

      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
      “”

      Reply
      1. Amit Sonkhiya says:

        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/

        Reply
        1. MadMax says:

          Hello Amit,

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

          Reply
  49. Javid Rad says:

    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 😉

    Reply
    1. Amit Sonkhiya says:

      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.

      Reply
  50. David Duong says:

    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

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
  51. Md Al Amin says:

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

    Reply
  52. Mickael Lambert says:

    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!

    Reply
    1. Amit Sonkhiya says:

      Hi,

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

      Reply
  53. Vaishali Bansal says:

    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

    Reply
      1. Vaishali Bansal says:

        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.

        Reply
        1. Amit Sonkhiya says:

          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’ );

          Reply
          1. Vaishali Bansal says:

            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

          2. Amit Sonkhiya says:

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

          3. Vaishali Bansal says:

            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.

          4. Amit Sonkhiya says:

            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.

        2. cmurphy says:

          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

          Reply
          1. Amit Sonkhiya says:

            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/

  54. Sharaz Hossein says:

    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?

    Reply
    1. Amit Sonkhiya says:

      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.

      Reply
      1. Sharaz Hossein says:

        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?

        Reply
  55. Sharaz Hossein says:

    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?

    Reply
    1. Amit Sonkhiya says:

      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.

      Reply
  56. Kirill says:

    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.

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
  57. Aaron says:

    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. 🙁

    Reply
    1. 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.

      Reply
        1. Aaron says:

          /* 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 );

          Reply
  58. MadMathilda says:

    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 🙂

    Reply
    1. 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.

      Reply
          1. rex says:

            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 ^_^

      1. nmfifi says:

        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.

        Reply
      2. Carl says:

        Hi Amit,

        first of all, thanks for this most usefull tutorial ,super.

        please email me the solution for this too.. (user receives a verification Email to fulfill the registration)
        Thanks

        Reply
  59. lawless99 says:

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

    Reply
  60. Tomáš Halo says:

    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

    Reply
    1. Amit Sonkhiya says:

      Hi,

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

      Thanks

      Reply
      1. Tomáš Halo says:

        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!

        Reply
  61. Adam says:

    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

    Reply
    1. Amit Sonkhiya says:

      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

      Reply
      1. Adam says:

        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

        Reply
        1. Amit Sonkhiya says:

          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.

          Reply
          1. Adam says:

            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

          2. Amit Sonkhiya says:

            Hi

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

      2. Adam says:

        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…

        Reply
      3. Adam says:

        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

        Reply
  62. MadMathilda says:

    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

    Reply
    1. Amit Sonkhiya says:

      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.

      Reply
      1. MadMathilda says:

        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? 🙂

        Reply
        1. Amit Sonkhiya says:

          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

          Reply
          1. MadMathilda says:

            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

          2. MadMathilda says:

            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

          3. ChrisBrowndog says:

            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

          4. Amit Sonkhiya says:

            Hi Chris,

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

  63. Mahu says:

    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

    Reply
    1. Amit Sonkhiya says:

      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 🙂

      Reply
      1. Amit Sonkhiya says:

        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/’)

        Reply
        1. Dannie Herdyawan says:

          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’

          Reply
          1. Dannie Herdyawan says:

            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?

          2. Amit Sonkhiya says:

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

          3. Amit Sonkhiya says:

            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.

          4. 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;

          5. Dannie Herdyawan says:

            Cool, it’s work..

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

  64. Amit Sonkhiya says:

    Vinod,

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

    Reply
    1. 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.

      Reply
      1. 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.

        Reply
      1. Amit Sonkhiya says:

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

        Reply
        1. Sukeshni says:

          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.

          Reply
          1. Amit Sonkhiya says:

            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.

  65. amritanshu kalia says:

    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

    Reply
    1. Amit Sonkhiya says:

      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.

      Reply
          1. Faham Shaikh says:

            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.

          2. Amit Sonkhiya says:

            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.

          3. Faham Shaikh says:

            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

  66. misad91 says:

    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

    Reply
    1. Amit Sonkhiya says:

      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.

      Reply
      1. Amit Sonkhiya says:

        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.

        Reply
    1. Amit Sonkhiya says:

      Misad,

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

      Reply
        1. Amit Sonkhiya says:

          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(),

          Reply

Leave a Reply