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
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <form id="login" class="ajax-auth" action="login" method="post"> <h3>New to site? <a id="pop_signup" href="">Create an Account</a></h3> <hr /> <h1>Login</h1> <p class="status"></p> <?php wp_nonce_field('ajax-login-nonce', 'security'); ?> <label for="username">Username</label> <input id="username" type="text" class="required" name="username"> <label for="password">Password</label> <input id="password" type="password" class="required" name="password"> <a class="text-link" href="<?php echo wp_lostpassword_url(); ?>">Lost password?</a> <input class="submit_button" type="submit" value="LOGIN"> <a class="close" href="">(close)</a> </form> <form id="register" class="ajax-auth" action="register" method="post"> <h3>Already have an account? <a id="pop_login" href="">Login</a></h3> <hr /> <h1>Signup</h1> <p class="status"></p> <?php wp_nonce_field('ajax-register-nonce', 'signonsecurity'); ?> <label for="signonname">Username</label> <input id="signonname" type="text" name="signonname" class="required"> <label for="email">Email</label> <input id="email" type="text" class="required email" name="email"> <label for="signonpassword">Password</label> <input id="signonpassword" type="password" class="required" name="signonpassword" > <label for="password2">Confirm Password</label> <input type="password" id="password2" class="required" name="password2"> <input class="submit_button" type="submit" value="SIGNUP"> <a class="close" href="">(close)</a> </form> |
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.
1 2 3 4 5 6 | <?php if (is_user_logged_in()) { ?> <a href="<?php echo wp_logout_url( home_url() ); ?>">Logout</a> <?php } else { get_template_part('ajax', 'auth'); ?> <a class="login_button" id="show_login" href="">Login</a> <a class="login_button" id="show_signup" href="">Signup</a> <?php } ?> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | form.ajax-auth{ display: none; z-index: 999; position: fixed; top: 150px; left: 50%; width: 350px; margin-left: -200px; padding: 40px 25px 25px 25px; background-color: #FFFFFF; border-radius: 8px; font-family: Arial, Helvetica, sans-serif; box-shadow: 0 0 6px rgba(0, 0, 0, 0.2); color: #878787; font-size: 11px; } .ajax-auth h1, .ajax-auth h3{ font-family: 'Georgia', 'Times New Roman', Times, serif; font-weight: 100; color: #333333; line-height: 1; } .ajax-auth h1{ font-size: 27px; text-align: center; margin: 0 0 20px 0; } .ajax-auth h3{ font-size: 18px; text-align: left; margin: 0; } .ajax-auth h3 a{ color: #e25c4c; } .ajax-auth hr { background-color: rgba(0, 0, 0, 0.1); border: 0 none; height: 1px; margin: 20px 0; } .ajax-auth input#username, .ajax-auth input#password, .ajax-auth input#signonname, .ajax-auth input#email, .ajax-auth input#signonpassword, .ajax-auth input#password2{ border: 1px solid #EDEDED; border-radius: 3px 3px 3px 3px; box-shadow: 0 0 3px rgba(0, 0, 0, 0.1) inset; color: #333333; font-size: 15px; padding: 10px 10px 10px 13px; width: 325px; margin: 7px 0 20px 0; background-color: #F9F9F9; font-family: 'Georgia', 'Times New Roman', Times, serif; } .ajax-auth input#username:focus, .ajax-auth input#password:focus, .ajax-auth input#signonname:focus, .ajax-auth input#email:focus, .ajax-auth input#signonpassword:focus, .ajax-auth input#password2:focus{ background-color: #FFF; } .ajax-auth label.error{ display: none !important; } .ajax-auth input.error{ border: 1px solid #FF0000 !important; } .ajax-auth input.submit_button{ font-size: 13px; color: #FFF; border: 1px solid #b34336; background-color: #e25c4c; border-radius: 3px; text-shadow: 0 1px 0 #ba3f31; padding: 9px 31px 9px 31px; background: -moz-linear-gradient(top, #ea6656, #df5949); border-top: 1px solid #bb483a; border-bottom: 1px solid #a63b2e; float: right; box-shadow: 0 1px 0 #E87A6E inset; } .ajax-auth a{ text-decoration: none; } .ajax-auth a.close{ color: #DCDCDC; position: absolute; right: 15px; top: 15px; } .ajax-auth a.text-link{ color: #B4B2B2; float: left; margin: 10px 0 0 0; } .ajax-auth p.status{ text-align: center; margin: -15px 0 20px 0; font-weight: 600; display: none; } a.login_button{ font-family: Arial, Helvetica, sans-serif; padding: 5px 7px 5px 7px; background-color: #FFF; border-radius: 3px; border: 1px solid #DCDCDC; color: #333; text-decoration: none; font-size: 11px; } .login_overlay{ height: 100%; width: 100%; background-color: #F6F6F6; opacity: 0.9; position: fixed; z-index: 998; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | jQuery(document).ready(function ($) { // Display form from link inside a popup $('#pop_login, #pop_signup').live('click', function (e) { formToFadeOut = $('form#register'); formtoFadeIn = $('form#login'); if ($(this).attr('id') == 'pop_signup') { formToFadeOut = $('form#login'); formtoFadeIn = $('form#register'); } formToFadeOut.fadeOut(500, function () { formtoFadeIn.fadeIn(); }) return false; }); // Close popup $(document).on('click', '.login_overlay, .close', function () { $('form#login, form#register').fadeOut(500, function () { $('.login_overlay').remove(); }); return false; }); // Show the login/signup popup on click $('#show_login, #show_signup').on('click', function (e) { $('body').prepend('<div class="login_overlay"></div>'); if ($(this).attr('id') == 'show_login') $('form#login').fadeIn(500); else $('form#register').fadeIn(500); e.preventDefault(); }); // Perform AJAX login/register on form submit $('form#login, form#register').on('submit', function (e) { if (!$(this).valid()) return false; $('p.status', this).show().text(ajax_auth_object.loadingmessage); action = 'ajaxlogin'; username = $('form#login #username').val(); password = $('form#login #password').val(); email = ''; security = $('form#login #security').val(); if ($(this).attr('id') == 'register') { action = 'ajaxregister'; username = $('#signonname').val(); password = $('#signonpassword').val(); email = $('#email').val(); security = $('#signonsecurity').val(); } ctrl = $(this); $.ajax({ type: 'POST', dataType: 'json', url: ajax_auth_object.ajaxurl, data: { 'action': action, 'username': username, 'password': password, 'email': email, 'security': security }, success: function (data) { $('p.status', ctrl).text(data.message); if (data.loggedin == true) { document.location.href = ajax_auth_object.redirecturl; } } }); e.preventDefault(); }); // Client side form validation if (jQuery("#register").length) jQuery("#register").validate( { rules:{ password2:{ equalTo:'#signonpassword' } }} ); else if (jQuery("#login").length) jQuery("#login").validate(); }); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | <?php function ajax_auth_init(){ 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'); wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'redirecturl' => home_url(), 'loadingmessage' => __('Sending user info, please wait...') )); // Enable the user with no privileges to run ajax_login() in AJAX add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' ); // Enable the user with no privileges to run ajax_register() in AJAX add_action( 'wp_ajax_nopriv_ajaxregister', 'ajax_register' ); } // Execute the action only if the user isn't logged in if (!is_user_logged_in()) { add_action('init', 'ajax_auth_init'); } function ajax_login(){ // First check the nonce, if it fails the function will break check_ajax_referer( 'ajax-login-nonce', 'security' ); // Nonce is checked, get the POST data and sign user on // Call auth_user_login auth_user_login($_POST['username'], $_POST['password'], 'Login'); die(); } function ajax_register(){ // First check the nonce, if it fails the function will break check_ajax_referer( 'ajax-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['first_name'] = $info['user_login'] = sanitize_user($_POST['username']) ; $info['user_pass'] = sanitize_text_field($_POST['password']); $info['user_email'] = sanitize_email( $_POST['email']); // Register the user $user_register = wp_insert_user( $info ); 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'=>__('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 { auth_user_login($info['nickname'], $info['user_pass'], 'Registration'); } die(); } function auth_user_login($user_login, $password, $login) { $info = array(); $info['user_login'] = $user_login; $info['user_password'] = $password; $info['remember'] = true; $user_signon = wp_signon( $info, '' ); // From false to '' since v4.9 if ( is_wp_error($user_signon) ){ echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.'))); } else { wp_set_current_user($user_signon->ID); echo json_encode(array('loggedin'=>true, 'message'=>__($login.' successful, redirecting...'))); } die(); } |
Open the functions.php file of your theme and place the line there:
1 | require_once( get_template_directory() . '/libs/custom-ajax-auth.php' ); |
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
Hello,
Why if this is ajax login do you do a redirect after the ajax login? Isn’t the whole point of ajax not to reload the page?
The point is to present the form to the visitor instead of redirecting to a separate page to enter the credentials.
WP requires setting up fresh cookies and session data in the user’s browser and that can’t be done through JS or due to security concerns.
Hello Amit,
This is great, thank you! I’m not a pro so I learned a lot following your tutorial and making some some slight adaptations.
However, I’m still stuck with admin-ajax calls, as they return an error 400.
I can see that ajax_auth_init() is correctly started, but the following functions are never fired: ajax_login(), ajax_register(), auth_user_login()
Something wrong here?
function ajax_auth_init()
{
bfsim_dump_to_database("hello, ajax_auth_init() is fired!"); // test: writing message in DB if function is fired
wp_register_style('ajax-auth-style', get_stylesheet_directory_uri() . '/auth/css/ajax-auth-style.css');
wp_enqueue_style('ajax-auth-style');
wp_register_script('validate-script', get_stylesheet_directory_uri() . '/auth/js/jquery.validate.js', array('jquery'));
wp_enqueue_script('validate-script');
wp_register_script('ajax-auth-script', get_stylesheet_directory_uri() . '/auth/js/ajax-auth-script.js', array('jquery'));
wp_enqueue_script('ajax-auth-script');
wp_localize_script('ajax-auth-script', 'ajax_auth_object', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action('wp_ajax_nopriv_ajax_login', 'ajax_login');
// Enable the user with no privileges to run ajax_register() in AJAX
add_action('wp_ajax_nopriv_ajax_register', 'ajax_register');
// Enable the user with no privileges to run ajax_forgotPassword() in AJAX
add_action( 'wp_ajax_nopriv_ajax_forgotPassword', 'ajax_forgotPassword' );
}
Thank you if you can help, and Congratulations on your work!
Pierre
Well, I found the problem.
The JS script was calling ‘ajaxlogin’ while the function is named ‘ajax_login’…
Adding the underscore solved the issue.
The same for ajax_register and ajax_forgotPassword…
Thnaks again ! 🙂
Is there a way to include in the above code file uploa on registration ?
it was very helpful…….thanks
but download code link is not working, I tried many times to download the source code…….
after login show risistraion page on header
Hi,
I didn’t get you.
Can you please tell me how can I disable validation of the jquery.validate.js script in the form? If I want to use mine?
You can either add novalidate attribute to the form element or disable line #36 in the ajax-auth-script.js file.
But after that I get an error https://s3.amazonaws.com/tz9i2p4ymw/169q569e65658p30.jpg and a persistent error in “Sending user info, please wait …” do you know the possible reason for this? 🙁
This isn’t a jQuery error. It’s due to some issues in server-side PHP script execution. I suggest you to enable debugging and check the debug log to find the cause. Here is an article for your reference.
https://fellowtuts.com/wordpress/debugging-writing-custom-php-data-log/
thank you and how to add login from google or facebook without plugin in this form
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
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!!
Hi,
We’ll surely check sooner if there any trouble exists.
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.
Hi,
Thank you for your honest words. Altho, these posts are for intermediate developers, I will try to write posts for beginners as well.
Please prepare a profile editing guide
HI @burakmeteerdoan:disqus
We will try to provide the same.
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();
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
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.
hi sir idont know why it create two users in the same time
@kaisbo:disqus
The code doesn’t create two users twice. You might have one additional plugin installed to create user.
thank you this is the problem
Hi Amit,
In terms of security, how do you rate this approach from 1 to 5?
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
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.
I can not download the file please help me.
Hello,
What problem are you facing in downloading? I can easily download the same. It’s the direct download link. Try in another browser if you have trouble or check the download location in your browser/PC.
hi amit,
I follow these steps but there is no change in my site.
Login form is not shown anywhere.
Please help me.
-Shariful.
hello @@shariful_sabuj:disqus
Please provide the link to the page where you have applied the implementation.
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?
@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.
Hi. I have one question: How to register users for specific role (Subscriber) via this tutorial?
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.
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.
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.
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.
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.
The
check_ajax_referer ('ajax-register-nonce', 'security')
line in ajax_register() function should becheck_ajax_referer ('ajax-register-nonce', 'signonsecurity')
. Am I wrong?My bad! Thank you @ofyalcin:disqus for finding this mistake. Damn! Nobody could notice this since last 4 years.
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?
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.
😀 LoL.
So the correct use is
check_ajax_referer ('ajax-register-nonce', 'security')
. Right?Yes
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?
@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.
Okay Thanks for the heads up! If you find a solution please let me know 🙂
Did you find a solution, Logan? 🙂
@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.
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.
@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.
Hello Amit, I’m having the same problem. Can you suggest a solution for this?
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
Hello Milan
I can see that you haven’t enqueued CSS and JS files properly and they are failing to load. Inspect the page under Network tab in the browser console and you will come to know. Are you using a child theme?
For example, the following URL is failed to load:
https://www.shopaxio.com/wp-content/themes/excellent/js/jquery.validate.js?ver=4.9.8
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.
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.
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.
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 a few customizations in theme files and settings to work better for both, users and search engines. You can write at amit@astech.club or use the given link for further discussion:
https://www.astech.club/services/e-commerce-solutions/
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
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
Hi,
I hope you have gotten my reply from amit@astech.club regarding your inquiry
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
@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.
The page can reload but it need to redirect to the current page. Is it possible ?
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
It was not working it was adding a undefined in the URL and getting 404 page after changing. http://localhost:81/compile/2018/08/undefined
In this url get undefined in the end of url.
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.
Hi Amit,
Great tutorial!
Is it possible to upload files with the registration form as well? Here’s my full question:
https://stackoverflow.com/questions/50068231/uploading-files-to-a-user-upon-wordpress-registration-with-ajax-and-acf
Thank you so much!
Great article, man! Helped me a lot. Thanks so much!
Hi Amit, excellent tutorial thanks for sharing. I hope you can help me, i am having problem with the forms – when click the submit button it redirects to the same page. URL example http://coffeetie.test/login/ when click submit button it goes http://coffeetie.test/login/login ( page not found) any ideias what could be causing this redirect ? Thank you
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
hii amit can u help me to create a custom profile page for update user information?
Hi @disqus_i4vcRJRgdC:disqus
What type of help do you need? Write us to support@fellowtuts.com or submit form:
http://fellowtuts.com/contact/
hii amit , i want to change color when error message is shown,how can i change
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
hii how can i create a forgot password popup in this
Hi
Check the article http://fellowtuts.com/wordpress/forgot-password-with-ajax-in-wordpress-login-and-register/
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
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
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
hello @disqus_gkOfxqykfU:disqus
Please share us a link to your page where you have implemented login/signup links
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
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
I follow your code. When I click login/register in the form, it redirects to wp-login.
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.
Hello Ghulam,
After WordPress update, we will check our code. Meanwhile you can send us link to your WP website to let us review
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.
Hi Ghulam,
Sorry as I couldn’t notice your comment. Is that issue resolved?
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
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
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…
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 🙂
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
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
Thanks for article, great blog. Thanks!
Hello Amit, where should i include the ajax-auth-script.js ??
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 ,
ajax-auth-script.js?ver=4.6.1:77 Uncaught TypeError: jQuery(…).validate is not a function
I just solved it thanks !
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
Hi lujain,
I’m unable to assist you until I don’t have link to your page facing issue. Please provide us the url. If you wish to remain private, mail to support@fellowtuts.com
Hi,
How can redirect according to roles
Hi Sudhir,
Please read comments on this blog post, I have mentioned it here a few times
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.
Hi dave,
If you are using this in menu, you need add this menu item dynamically via code
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
));
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
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
Hi Roobiya
We perform the same through dynamically registering menu items via code in WordPress.
Thanks
hey can you plz tell me how that work. and i did everything as said in that blog. but its not working.
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
how can i solve this error message?
Uncaught TypeError: $(…).live is not a function
at HTMLDocument. (http://localhost/Authetic-Imported-Goods/wp-content/themes/underscores/js/ajax-auth-script.js?ver=4.6.1:4:31)
at i (http://localhost/Authetic-Imported-Goods/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:27449)
at Object.fireWith [as resolveWith] (http://localhost/Authetic-Imported-Goods/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:28213)
at Function.ready (http://localhost/Authetic-Imported-Goods/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:30006)
at HTMLDocument.K (http://localhost/Authetic-Imported-Goods/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:30368)
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.
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
i have the same problem can you tell how did you solve it ?
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 $().
Hi Amit,
Instead of placing buttons, can we auto populate modal box for login? If yes how to do that?
Hi, how do I set up this login / register ajax to show at the click of a button in my navigation menu?
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
Hi
Please check your email from support@fellowtuts.com
Thanks
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.
Hi Nicolas.
I think that you have solved the issues and edited the comment later. Glad to know that.
Thanks
Hi I don’t know how to link this to my Sql. Please explain that code also so that it will work for me.
Great & Helpful Tutorial. So easy to understand and use, Thanks for sharing with us.
I have also created another Ajax Login Form Using jQuery and PHP.
Awesome! Thanks you, Amit for this great tutorial.
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!
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.
Hello Anahit,
Please provide url of page where you are facing the issue. I can reply only after checking that
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!
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.
Use email_exists() and username_exists() functions provided by WordPress
Yes thank you very much!
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.
Any ideas?
Use add_user_meta() and get_user_meta() functions built into WP for the same
But how?
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
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
Hi Llia,
It’s quite tricky. You have to add them dynamically to the menu (example: http://www.wpbeginner.com/wp-themes/how-to-add-custom-items-to-specific-wordpress-menus/) and change the selector ids with your menu ids in ajax-auth-script.js (line #35) to fire the click event.
If you face any issue or wish us to do so for you, please write us at support@fellowtuts.com
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
hello,
Really thanks for your article. it works perfect for me. hope you will create more useful tutorials like this.
thanks again.
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.
Hi Anahit,
The email sending code should be placed inside ajax_register() function just before auth_user_login() call
Thanks
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.
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)
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.
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.
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
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.
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”;?>
Seems code did not displayed properly within my reply. I used the same code from here https://codex.wordpress.org/Function_Reference/get_currentuserinfo .So you could see the code there.
Thanks in advance.
It all depends on how are you coding? There might be some error in your code.
Write us at support@fellowtuts.com if you wish us to correct it.
Thanks
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?
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.
Hi,
You can use wp_mail function inside ajax_register() function
Thanks
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.
Hi Anahit,
The email sending code should be placed inside ajax_register() function just before auth_user_login() call
Thanks
i have error after send data. Redirect http://www.???.az//register
Hi Fall
what is your site url. I think you are pointing to some site with restrict keywords. Drop us email with this information at support@fellowtuts.com
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();
}
Hi Bobin
The code you provided is just registration process script. It doesn’t show how is this function called. I would need full code to have a look. You can write us to support@fellowtuts.com
Solved it , i had saved another file that was doing the same thing. Thanks again.
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?
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.
Glad you have rectified this.
Hi,
This is too better, I always use this..
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’);
Hi Dawid,
Is there any url to check the functionality?
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 🙂
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
Thanks Amit , this is very helpful info , appreciate 🙂
How would one go about converting this into a plugin ?
There are already plugins based on this tutorials
Hi Amit, can you please send me the same code for email verification on registration.?
my email id : farhankureshi71@gmail.com
Hello Farhan,
I have dropped you an email to afford-said address. Pleas check that
Thanks
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
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.
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.
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
Thanks for the awesome tutorial. 5 stars…
is there an easy way to modify this so that each individual field is checked via ajax call when the user moves focus to another field?
btw thanks for the great write up
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
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?
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
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/
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…
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
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/
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
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.
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
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?
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.
What’s up to every one, the contents present at this web site are truly amazing for people knowledge, well, keep up the good work fellows.
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 ?
please ans it
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.
thank you so much
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.”
Hi Rex,
I’m sorry to hear that. I have sent you an email from support@fellowtuts.com or also you can write us using http://fellowtuts.com/troubleshooting/ or http://fellowtuts.com/contact/
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
You should first check if are all necessary resources (css, js files) are included properly by inspecting browser source code of your page.
If you still face issues, you can upload your project to test server and write us at http://fellowtuts.com/troubleshooting/
I am confused how to check where is the error
I have sent you an email from support@fellowtuts.com. Please check your emails including spam folder as well.
Thanks
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.
Hi,
I have sent to an email regarding solution from support@fellowtuts.com hours ago. Please check the same (spam folder as well).
Thanks
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?
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”
“”
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/
Hello Amit,
thx for support! I´ve sent you a mail, you´ve got it? Hope you can help me for this modification?
Hi,
I have already sent you code almost 15 hours ago from support@fellowtuts.com address.
I’m sending you the same again from a gmail address. Please check back.
Ouh, ok, maybe my mailbox fails. I send you a new email adress. Big thx!
Did you get now? Check your spam folder as well.
Sry for late reply – yes, I´ve got it – big thx!! Awesome support here!
Please how do I contact you for a private chat on some BuddyPress issues.
Hi,
you can drop us a mail at support@fellowtuts.com along with Skype Id and some detail about the issue first.
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 😉
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.
We try it http://www.fashionedits.com/blog2/, but register form is showed and the layout is terrible.
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
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
This what I’m looking for. You are the man. Thanks. I bookmarked the site. Hope you’ll post more article I need 🙂
Hi Amit this is an excellent post can u tell me how can i integrate this with a plugin
You can download & modify that plugin with integrating our code. Knowledge of PHP & WP are required. If you it tough you can use our service: http://fellowtuts.com/troubleshooting/
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!
Hi,
Thanks for appreciation. We didn’t attempt to integrate social login into this. Do you need one?
You’re welcome.
Yes, i have no idea how to do it, but i’ll try in the week!
Sure, good luck and also I have dropped you an email from support@fellowtuts.com
Thanks
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
Hi,
Did you place the login/out links as described at http://fellowtuts.com/wordpress/wordpress-ajax-login-and-register-without-a-plugin/#crayon-554363385a325416370194-0
What is url of page where you have implemented the buttons?
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.
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’ );
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
I would like to suggest you to direct paste above code to header.php or anywhere else just to check if it works?
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.
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.
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
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/
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?
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.
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?
Sure. We would try our best.
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?
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.
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.
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
I have checked my website error log. It is clear. Could you advise any other diagnostic please.
Hellow Kirill,
Please check functions.php file in your active theme and remove any spaces, empty lines or line breaks before and after opening & closing php tags respectively.
Also you may find this article helpful: http://fellowtuts.com/wordpress/wordpress-fix-to-blank-screen-or-blank-page-or-dashboard/
Thanks
Hello, i reached the step to insert require_once( get_template_directory() . ‘/libs/custom-ajax-auth.php’ ); into the functions.php. I recieved an error
Warning:
require_once(/hermes/bosnaweb04a/b2721/ipg.ghanarecipecom/wp-content/themes/inspirythemes-food-recipes/libs/custom-ajax-auth.php):
failed to open stream: No such file or directory in
/hermes/bosnaweb04a/b2721/ipg.ghanarecipecom/wp-content/themes/inspirythemes-food-recipes-child/functions.php
on line 18
Fatal error: require_once(): Failed opening required
‘/hermes/bosnaweb04a/b2721/ipg.ghanarecipecom/wp-content/themes/inspirythemes-food-recipes/libs/custom-ajax-auth.php’
(include_path=’.:/usr/local/lib/php-5.3.13/lib/php’) in
/hermes/bosnaweb04a/b2721/ipg.ghanarecipecom/wp-content/themes/inspirythemes-food-recipes-child/functions.php
on line 18
I need help. 🙁
Hello Aaron,
I think you forgot to place the custom-ajax-auth.php file in lib directory of the them. Please check once. If not found there, download from here and place it in lib directory of your current theme.
Hi,
As you mentioned, I can sense that you are using child theme and you have placed file in parent theme. Please try with shifting file to child and also validate that necessary js/css files can be loaded by inspecting path in browser’s source code.
https://codex.wordpress.org/Function_Reference/get_template_directory
Hmm. Have a look at my functions.php file code>>
** and I placed the file in the correct path.
You are using customization in code provided by us. So we are not sure that what is going wrong. For further assistance, please follow our troubleshooting service
http://fellowtuts.com/troubleshooting/
/* 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 );
Hello Amit,
is there any way to improve the registration form in a Double Opt-in process? So that the user receives a validation key (maybe just the same random key as from the forgot password form) which he has to enter to fulfill the registration?
In that way the user verifies his Email.
Or is this only possible using the random wordpress registration form?
Best Regards,
Mathilda 🙂
Hello MadMathilda,
Yes, we can do it by sending an email to user with new randomly generated password which will be used for first time login by the user.
After inserting user in wp, we can shoot an email to the user. I think this will help you to get the point.
Hi MadMathilda,
Welcome back!
I just dropped you an email regarding the solution.
Thanks
Hi Amit, can you please mail me the same code which is responsible for email verification on registration.
my email id : onilledigital.robin@gmail.com
Hi,
Please check gmail from support@fellowtuts.com
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 ^_^
Hi Rex
I have sent you an email from support@fellowtuts.com
Hi Amit, can you please send me the same code for email verification on registration.?
my email id : farhankureshi71@gmail.com
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.
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
Hello @Carl
Thank you for finding this article useful. Please submit a request using the link given below for the solution:
https://www.astech.club/services/wordpress-development-themes-plugins/
Hi,
How can I proceed to use ajax login/register with buddypress?
What changes should I make?
Thanks
Hi,
As the question is not directly related to post still to integrate it with BuddyPress you are requested to use our troubleshooting services (http://fellowtuts.com/troubleshooting/)
Beautiful tutorial – I have successfully implemented this in my site management plugin. Thank you very much Amit!
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
Hi,
Thanks for appreciation and support. We would be glad to implement the function as you wish. Let me know what is desired!
Thanks
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!
Hi Tomas,
My reply will arrive in your inbox in a few minutes.
Thank you.
Hi Amit,
can you send me the same solution?
Thanks!
Hi,
I have sent you an email.
Thanks.
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
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
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
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.
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
Hi
There is some issue with php script in the file at your end and it’s unable to return the response..
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…
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
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
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.
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? 🙂
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
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
Hello Mathilda,
i found that you implemet terms of use into registration form in your website http://www.sportsbuddies.de/ (Ich habe die Datenschutzrichtlinien und… )
Can you help me how to do it right way?
Thanks for your help
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
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
Hi Chris,
We are testing the AJAX login with reCaptcha script & hope will post new ready to implement article very soon.
Hello Chris,
look at the code of this plugin (https://wordpress.org/plugins/ciusan-register-login/) – it is based on this tutorial and is also implement google recaptcha as well.
Hi,
Please follow the article http://fellowtuts.com/wordpress/implementing-google-recaptcha-in-wordpress-ajax-register/ and download zip.
Thanks
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
I suspect there is any jQuery related issue stuck with your site. Will you please provide the link to your page?
Thank you so much for your fast reply, the homepage is: http://184990.webhosting29.1blu.de/sportsbuddies/
It is still under construction.
The two links are on the left side of the page, just above the blue box.
Since i tried to install this Ajax Plugin also the Masonry Plugin (http://184990.webhosting29.1blu.de/sportsbuddies/) is broken.
Best regards,
Mahu
You were right, it was a rquery conflict. Got it fixed. Thank you again.
Great! You have fixed that.
Bro, I’m experiencing exactly the same issue. How did you fix it on your end? Thanks in advance.
Hi, thanks for great tutorial… I created this tutorial and using with my site http://www.ciusan.com… Can I create a plugin with this tutorial and upload them in to a wordpress plugin?
Regards,
Dannie Herdyawan
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 🙂
Hai, this the link: https://wordpress.org/plugins/ciusan-register-login/
But, i want to ask, i want if succesfull login redirect to http://www.ciusan.com/profile, and if new registered redirect to thanks page.. How??? Thanks…
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/’)
Yeah, thanks….. 😀
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’
Yup! you can change it to wherever you wish to redirect the user.
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?
Dannie, I have updated my previous reply and added one more variable there. Please check that and let me know.
Is it also possible to redirect the user to the page which he last viewed?
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.
That is exactly what i wanted to achieve. Works perfect, thank you very much.
Dannie.. you can change this line in your ajax-auth-script.js file :
document.location.href = $(this).attr (‘id’) == ‘register’ ? ajax_auth_object.register_redirect : ajax_auth_object.redirecturl;
replace it with –
document.location.href = $(ctrl).attr (‘id’) == ‘register’ ? ajax_auth_object.register_redirect : ajax_auth_object.redirecturl;
Cool, it’s work..
Thank you very much K K Agrawa….
Thanks also to you Amit Sonkhiya, who has made this tutorial…
Sorry, still not working ….. Or I must to send the file, and you check it?
This the file:
http://www.ciusan.com/ciusan-register-login.zip
Vinod,
There is zM Ajax Login & Register plugin install there which is causing the issue. Please remove that one first.
Hi Amit,
Very thank you for the tutorial.
how to create forget password form?
Thanks!
Sandi
Please refer this article: http://fellowtuts.com/wordpress/forgot-password-with-ajax-in-wordpress-login-and-register/
Hi Amit,
Thank you very much for the tutorial.
I see that it doesn’t log me in rather it says: “Sending user info, please wait…”
Please help.
I followed all the steps mentioned.
Hi Amit,
I got it to work, but the dashboard panel on the top doesn’t show up immediately after loggin in. But I had to refresh multiple times to show the “Logout” button and WordPress dashboard panel.
What can be done for this? Please help.
Are you using any wordpress caching plugin. If yes, please clear the cache first. If you still have issue then Please tell us your website url where you have implemented this so that we can check here and let you know the solution.
Hi Vinod,
I am getting the same problem.
Please help.
Hello,
This error occurs if there is some issue in processing functions in custom-ajax-auth.php. Please provide your site link.
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.
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.
Great! Thank you very much!
Thank you
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
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.
Hi Amit,
I am having the jquery validate but I am still getting 404
I suggest you to mention the steps you followed for ajax login or provide url where you are facing issue. You can use http://fellowtuts.com/contact/ if you wish to remain private.
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.
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.
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
Glad to hear that you have sorted out the problem.
Still if you are unable to resolve the issue then please give me the link to your website.
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
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.
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.
How to redirect user to another page if login is successful?
Misad,
Under the Handling the AJAX Request section, change home_url() with home_url(‘/PageName/’) for redirecturl (line number #14)
thanks
Can I redirect user to another page for only register form?
You can change id of link that opens register popup and specify href attribute to desired page
<a href="”>Logout
Login
Signup
Thanks !
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(),
good