Website Guider

The Ultimate Resource for WPadmins and Geeks

How To Create An Ajax Login In WordPress Without Plugin

Hey, Are you looking for a tutorial on creating an ajax login form in WordPress without a plugin?

This article will show you how to create an ajax login in WordPress without plugin most easily and quickly.

Lets start.

Why Do You Need Ajax Login Form?

Ajax is the best way to let users log in or sign in to the website without interfering with the browser. Ajax is the best way to increase user experience.

There are many reasons for adding ajax login functionality to your website. The few are listed below.

  • You want to replace the old fashioned login form.
  • You don’t want your browser should be reloaded when the user submits credentials.
  • You want to increase the user experience of your website.

There may be hundreds of reasons for using ajax login functionality. So, without wasting our precious time, lets dive straight in to the code.

Creating A Template

The first step of our code is to create a template file. We wouldn’t create any plugin, so I assume you are using the Twenty Twenty default theme.

Inside the theme, create a file and name it wg-ajax-login-template.php . Inside the file, paste this code.

<?php

/**
 * Template Name: Ajax Login
 * Template Post Type: page
 *
 * @package WordPress
 * @author WebsiteGuider
 */

get_header();

if (is_user_logged_in()) {
	echo '<p class="logged-in">You are already Logged In</p>';
} else {
	?>

	<div class="wg-ajax-login">
		<div class="wg-ajax-login-inner">
			<form action="" method="POST">
				<p class="wg-msg">
				</p>
				<p class="wg-user-field">
					<label>Username or Email</label>
					<input type="text"  class="wg-username-email" name="wg-username-email" placeholder="Please Enter Here...">
				</p>			
				<p class="wg-user-field">
					<label>Password</label>
					<input type="password" class="wg-password" name="wg-password" placeholder="Please Enter Here...">
				</p>
				<p class="wg-submit">
					<input type="submit"  class="wg-ajax-submit" name="wg-ajax-submit" value="Sign In">
					<?php wp_nonce_field( 'wg_ajax_nonce_check', 'wg_ajax_nonce' ); ?>
				</p>
			</form>
		</div>
	</div>
	<?php
}
get_footer();

In the above code, I am creating a template named as Ajax Login. Then I call get_header() at the top and get_footer() at the bottom to get our default theme header and footer.

The next step I do is check if the user is already logged in and notify him he is already logged in.

If the user isn’t logged in then show him the login form.

Did you notice something inside HTML form? I used nonce for security. Please read this tutorial regarding nonce.

Creating a JavaScript File

We have created a template successfully. Now, let’s move towards client-side Javascript for a short time, and then we will come back with server-side PHP.

We will use the JQuery library for our ajax call. So jQuery is a dependency of this code. Be sure to check whether jquery is included or not in the frontend.

So, create a file inside the assets/js folder in activated theme (in my case, it is Twenty-Twenty) and name it wg-ajax-login.js. If you are not using the default theme, then be sure to create a file inside your theme. But remember the path where you will store your file.

Inside the file paste this code.

jQuery(document).ready(function($) {
	$(".wg-ajax-submit").on('click', function(e) {
		var admin_url = wg_ajax_login_object.ajax_url;
		$.ajax({
			type: 'POST',
            dataType: 'json',
            url: admin_url,
            data: {
                'action': 'wg_ajax_login_handler', //calls wp_ajax_nopriv_ajaxlogin
                'wg_username': $('.wg-username-email').val(),
                'wg_password': $('.wg-password').val(),
                'nonce': $('#wg_ajax_nonce').val()
            },
            beforeSend: function(){
            	// Show user a message that details are being checked
            	$('.wg-msg').text(wg_ajax_login_object.beforeMessage);
            },
            success: function (data) {
                if (data.loggedin == true) {
                	// Show success message if user details exist
                	$('.wg-msg').text(wg_ajax_login_object.successMessage);
                	// Create timer to refresh page after successfull login
                    setTimeout(function(){
                    	document.location.href = wg_ajax_login_object.redirectUrl;
                    }, 2000);
                } else if ( data.loggedin == false ) {
                	// Show failure message if user details doesn't exist
                	$('.wg-msg').text(wg_ajax_login_object.failureMessage);
                }
            }
		});
		e.preventDefault();
	});
});

There is lot going inside this file. Let me explain it in list.

  • Firstly, I create a variable which stores our URL where the data will be submitted.
  • Then the ajax starts where I have provided few options to it, which are required. I have used the POST method and set the dataType to JSON because we will receive data in JSON.
  • Then I use data property, which stores our action, which we will use to register an action. And I store a few values which we need like users’ email or password.
  • After that, I use beforeSend so the user will know that something is happening.
  • Finally, if our request’s status code is 200, we show the user a few messages that we will declare inside the functions.php file.

Editing functions.php

Everything is fine now. But nothing will happen because we didn’t include the JS file in our code. Let’s do it.

Find the functions.php file inside your theme folder and scroll to bottom and add this code to it.

add_action( 'init', 'wg_enqueue_scripts' );
function wg_enqueue_scripts() {

	if ( is_user_logged_in() ) {
		return;
	}

	wp_register_script( 'wg-ajax-login', get_template_directory_uri() . '/assets/js/wg-ajax-login.js', array( 'jquery' ) );
	wp_enqueue_script('wg-ajax-login');
	wp_localize_script( 'wg-ajax-login', 'wg_ajax_login_object', array(
		'ajax_url' 			=> admin_url('admin-ajax.php'),
		'redirectUrl'		=> get_home_url() . '/wp-admin',
		'beforeMessage' 	=> 'Checking credentials, please wait...',
		'successMessage'	=> 'Succesfully Logged In, you will be redirected shortly',
		'failureMessage'	=> 'Wrong credentials provided, please try again...',
	) );

	add_action( "wp_ajax_nopriv_wg_ajax_login_handler", 'wg_ajax_login_handler' );

}

function wg_ajax_login_handler() {
	// Check nonce
	check_ajax_referer( 'wg_ajax_nonce_check', 'nonce' );

	$userInfo = array();
	$userInfo['user_login'] = trim($_POST['wg_username']);
	$userInfo['user_password'] = trim($_POST['wg_password']);

	$userSignIn = wp_signon($userInfo, false);
	if ( is_wp_error( $userSignIn ) ) {
		echo json_encode(array('loggedin' => false));
	} else {
		echo json_encode(array('loggedin' => true));
	}

	wp_die();

}

I use the init hook to add our Javascript file to the frontend only. Inside the defined action callback function wg_enqueue_scripts() I check whether the user is logged in or not; if the user isn’t logged in, then continue.

After that, I include the JavaScript file. Then, I use wp_localize_script() to internationalize JavaScript object wg_ajax_login_object , which stores the messages we use earlier. At last, I populate the no privileged ajax hook.

Inside wg_ajax_login_handler() I check for nonce first. If the nonce matches then move forward else don’t execute remaining code.

Finally, I use the wp_signon() function, which handles our WordPress-powered website’s sign-in process.

Create a Login Page

The last step of our ajax login functionality is to create a page and then show the HTML form to the non logged in users.

Visit the dashboard section of your website, create a page, and name it as Login Page or other, which suits you.

After creating a page, set its template to Ajax login, and hit publish. Visit the page and you are done.

How To Create An Ajax Login In WordPress Without Plugin 1
Set template to Ajax Login

Conclusion

I hope the above code helped you create an ajax login page in WordPress without using a plugin. If the code doesn’t work in any case, drop a message inside the comment box, and I will help surely.

If the tutorial helped you, then please don’t forget to share and drop a comment. Also, please do subscribe to our YouTube channel.

Raashid Din Dar

Raashid Din Dar is a web developer and designer. He specialises in WordPress Theme and Plugin development. Also, Web Designing is what he loves.He loves to read books and play with friends.

3 thoughts on “How To Create An Ajax Login In WordPress Without Plugin

  1. Hey there! Someone in my Myspace group shared this website with us so I came to give it a look. Maye Aldous Trakas

  2. Nice articles. Its working. Implemented its my custom login for user. And I changer ‘redirectUrl’ => get_home_url() . ‘/wp-admin’, to ‘redirectUrl’ => home_url().
    And enter admin username and password its redirect to my website. From here i try to access my wp-admin(dashboard) it shows “redirected you too many times.
    Try clearing your cookies.
    ERR_TOO_MANY_REDIRECTS” . How to solve this

    1. Hi,
      I can assist you better if you show the changes you have made to the code.
      Otherwise, you can clear the cookies of your site and remember to flush the WordPress cache.
      Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top