Forgot Password with AJAX in WordPress Login and Register

After getting many requests from visitors to integrate Forgot Password with AJAX in my previous article WordPress AJAX Login and Register without a Plugin I decided to write a post about steps and code to add in that article to include Forgot Password functionality. This article is an improvement over that previous article as well as it will be sure helpful to understand how does the functionality actually work.

Forgot Password with AJAX in WordPress

The form opens as popup when you click ‘Lost password‘ link given inside ‘Login‘ popup and send an email to validated user after setting new password in WordPress database. You can download the complete zip of files at the end of this post to add in your theme to implement AJAX Login, Register and Forgot Password without a plugin and powered with jQuery client side validation.

Forgot Password with AJAX in WordPress Login and Register

The Form

Starting from ajax-auth.php file we have added a form there to obtain input by user.

 CSS

To style the input textbox and submit button, we are adding .ajax-auth input#user_login and .ajax-auth input#user_login:focus classes after line numbers 53 and 71 respectively in ajax-auth-style.css and code are highlighted below:

Script 

The script part handles showing the form, validates the textbox, sends information inputted by user to server and notifies user as per the response received through AJAX. Methods added into ajax-auth-script.js are

Handling the AJAX Request 

In custom-ajax-auth.php that does all server side processing, we have added just one line as WordPress action hook to call ajax_forgotPassword() as well as the function itself. So the modified code is:

The code block is self explanatory and we have used  a number of WordPress inbuilt functions here as defined in global wbdb class. We are  trying to match user input with an existing user in database through email first and then username (if input is not an email) as well as added error in case of empty/invalidated or non-existing user.

If a user matches then we tried to assign it a new password, update the database table and attempted to send new password to the user.

NOTE: Please provide a valid email address for sender field ($from at line number 8) otherwise system will use ‘admin@yoursite.com’ as default sender (yoursite.com will get replace with your domain name).

It’s all about embedding Forgot Password functionality in AJAX Login and Register without a Plugin in WordPress.

Download Zip

Included: ajax-auth-style.css, jquery.validate.js, ajax-auth-script.js, ajax-auth.php, custom-ajax-auth.php (updated for Forgot Password with AJAX)

Or if you are intended to just use login and register without a plugin then please refer to this tutorial.

You Might Interested In

49 COMMENTS

  1. celsaseiffert96 says:

    Cool blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog shine. Please let me know where you got your theme. Thanks

    Reply
  2. Francesco Fries says:

    Very nice post. I just stumbled upon your weblog and wanted to say that I’ve really enjoyed browsing your blog posts. After all I will be subscribing to your feed and I hope you write again soon!

    Reply
  3. Doreen Farrar says:

    Hey! Would you mind if I share your blog with my facebook group? There’s a lot of people that I think would really enjoy your content. Please let me know. Many thanks

    Reply
  4. Monika Layh says:

    You really make it appear really easy with your presentation but I find this matter to be actually something which I think I would never understand. It kind of feels too complex and very extensive for me. I am looking ahead to your next put up, I’ll try to get the grasp of it!

    Reply
  5. Bonita Tobin says:

    Hello! I could have sworn I’ve been to this site before but after looking at many of the posts I realized it’s new to me. Anyhow, I’m certainly pleased I stumbled upon it and I’ll be bookmarking it and checking back frequently!

    Reply
  6. Julien David B says:

    U just rox saved me quite a couple of hours 😉

    Also it could be nice to make the password expirable or send a link that goes into a new password page creation instead of receiving the password.
    Dunno what is safer. Any ideas?

    Reply
    1. Amit Sonkhiya says:

      @juliendavidb:disqus

      Sending the password reset link is always better. However, most of the users feel comfort to keep code easy and understandable. You can replace the the code in ajax_forgotPassword() function to send the reset link. The SO answer might help you:

      https://wordpress.stackexchange.com/questions/60318/sending-the-reset-password-link-programatically

      We would be also happy to implement that for you. Just write me at amit@astech.solutions or use the link:

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

      Reply
  7. farnam says:

    How to show other fields during user registration like nickname display name or first name?
    how to change Forgotten Password reset function to send a link to reset password instead send new password via email ?

    Reply
    1. Amit Sonkhiya says:

      Hi @disqus_i4vcRJRgdC:disqus

      The function responsible to send email is being called twice. Check your server side code carefully & correct it.

      Alternatively, it you’re using some other code/plugin to perform the same, that might also cause the issue.

      Reply
  8. Sarath Chandran says:

    hii amit,
    i need a help , in your code , a random password is sending to mail.but i need change my password .how can i do that

    Reply
  9. An interesting discussion is definitely worth comment. There’s no doubt that that you need to write more on this topic, it might not be a taboo matter but generally people don’t talk about such topics. To the next! Kind regards!!

    Reply
      1. Vysakh Gopalakrishnan says:

        ya i tried that but after few minutes i get only a blank msg from that ,it not contain any link for passsword updation

        Reply
  10. sumit saurav says:

    Hi Amit,
    i am using WPLMS theme and i want onclick image login and registration form will come in popups and when user register ,automatically user logged in and redirect to same page .
    i have download your code but i don’t know how to use in wordpress.
    Can you help me ?

    Reply
  11. Dan Dulaney says:

    Hello! I found a small error in your script, which also relates to the question by Gregory Mathews about it forcing re-login for admin section.

    You use wp_set_current user, to log in. According to the codex, this is not enough to log a user in, and you must also:

    wp_set_auth_cookie( $user_id );

    do_action( ‘wp_login’, $user->user_login );

    https://codex.wordpress.org/Function_Reference/wp_set_current_user#Examples

    My whole else block is as follows, in the custom-ajax-auth.php file:

    else {
    $user = get_user_by( ‘id’, $user_signon->ID);
    wp_set_current_user($user_signon->ID, $user->user_login);
    wp_set_auth_cookie( $user_signon->ID );
    do_action( ‘wp_login’, $user->user_login );
    echo json_encode(array(‘loggedin’=>true, ‘message’=>__($login.’ successful, redirecting…’)));
    }

    Thank you!

    Reply
  12. knolaust says:

    I keep getting “Cannot create a user with an empty login name.” when trying to use the register feature. Any suggestions? I’ve plugged the code in exactly as it is downloaded.

    Reply
    1. Amit Sonkhiya says:

      Hi knolaust

      It seems that POST parameters are not passing to server correctly. Can you check what are being passed from browser using firebug and what is received at server using var_dump($_POST);

      Reply
      1. knolaust says:

        Nothing. It’s passing the security and that’s it. Here’s the form for register (note: login and forgot password work). I may have stared at this so long that I’m missing something obvious.

        Become a Member

        First, let’s setup a username and password. Then you can complete the application.

        Username

        Email

        Password

        Confirm Password

        Already have an account? Login

        Reply
  13. Anahit Aida Ghazaryan says:

    Thank you for the working tutorial.

    Is there a way to allow users to set their new password what they want within the forgot password section instead of giving them generated password please?

    Thanks in advance.

    Reply
  14. Archil says:

    You have an error in your files, in cusom-ajax-auth.php you check_ajax_referer in all three ways with parameter “security”, but it must be “security”, “signonsecurity” and “forgotsecurity”

    Reply
  15. Quick question (awesome work BTW): if I successfully login using my ADMIN CREDS, then attempt to navigate to the WP ADMIN area, I am redirected to the default WP Login page and logged out of my current session. Is this a security thing with WP in the way the Custom WP AJAX Login works? Thanks again for contributing to the community.

    Reply
    1. Amit Sonkhiya says:

      Hi Gregory
      There is no such default implementation by WordPress. I suggest you to review plugins you have installed in your site, they might cause the issue.

      Thanks for your kind words.

      Reply
      1. Hi Amit,

        What if we wanted to use the Password Reset via link option (like WP does by default) in lieu of generating one on the user’s behalf and emailing them the result? Can that be accomplished via your code as well? This would help prevent “unauthorized” password resets as the user would have to click the link in the email to actually choose and reset their password.

        G.

        Reply
  16. Nico says:

    Hi, I have been playing woth your script for a site of my own and found that It lets you register even if you put to different passwords in the form.

    And just something that happens to me is that I can’t recover the password as it says “System is unable to send you mail containg your new password.” I am trying it in localhost, might that be the reason?

    Regards and thanks!

    Reply
    1. Amit Sonkhiya says:

      Different password with? What about Username?

      Yes your mailserver at localhost is not configured that’s why you are getting the message. It will work fine on live.

      Reply
      1. Nico says:

        I mean that if in the register form you type two different valuesfor the password and confirm password field, the form is submitted anyway.

        Reply
          1. Nico says:

            Great, many thanks!
            I have been trying to fix it but it exceeds my knoledge apparently… tryied many ways and couldn’t.
            Anyway, I will be waiting!

            Thanks again

          2. Amit Sonkhiya says:

            Hi,

            I have updated the code. A jQuery implementation has been made at end in ajax-auth-script.js. Download the updated files.

            Thanks.

  17. GiuseppeTr says:

    Hi,

    I have added the forgot password script.

    But when I click “forgot password ?” in login form, it goes to default forgot page “wp-login.php?action=lostpassword”

    Thanks!

    Reply

Leave a Reply