Light Weight WordPress Frontend Ajax Login and Registration

Posted by & filed under CSS, HTML5, JQUERY, MYSQL, PHP, WORDPRESS.

In this tutorial we are going to see WordPress frontend Ajax login and registration without using any plug-in. Once I thought Implementing frontend login in WordPress by own is one of the biggest diffcult task we ever do, but now it’s one easiest thing we ever do. So now we are implement this easiest thing in your project or blog just following few simple steps.
By default WordPress disables following GLOBAL variables POST, GET, SESSION and REQUEST for security reasons. So I think it very easy to done this WordPress login and registration using WordPress Ajax request.

Advantages of Script Over WordPress Login Plugin:

1. Most of time we can not trust plugin authors code that’s Most efficient or not. So myself coded this WordPress Frontend Login and Registration functionality for my blog.
2. This script doesn’t have unwanted functionality code as well as It doesn’t load unwanted script. I think one of the light weight script for WordPress login and registration functionality.
3. It has frontend validation as well as server side validation.
4. It very easy to implement in your project.

 

 

Wordpress Frontend Ajax Login and Registration

WordPress Frontend Registration and Login Form:

In this previous tutorial I had made tutorial on this WordPress Frontend Registration and Login Form. Please refer following tutorial to design your own WordPress Frontend Login, Registration and Forget Password form.

Login, Sing Up & Forget Password Modal Form Using Bootstrap

Please download the source file from above tutorial, if you needed.

Registering WordPress Ajax Call In Functions.php:

Before we are going to do any functions in particular Frameworks (WordPress or CakePHP),  we need to study it’s conventions and follow it, it will simplify our work as well as we will not break it security features most of time.

 

 

To make ajax request from frontend side in WordPress we need to do following things.
That’s I am using ajax.js file where I kept all the script to make ajax request. So we must enqueue this ajax.js script in functions.php.

wp_enqueue_script()  WordPress:
It add specified the script file to the generated page at the right time according to the script dependencies.

Next we need to declare JavaScript Global variables in our functions.php file using wp_localize_script() function.

<?php wp_localize_script( $handle, $name, $data ); ?>  

Where $handle – refers to script file
$name – refers to name of the JavaScript object.
$data – where we can specify list parameters for that JavaScript object ($name) going to have.

wp_register_script( 'ajax', get_template_directory_uri() . '/library/js/ajax.js', array('jquery'), '1.2' );
wp_enqueue_script( 'ajax' );
wp_localize_script( 'ajax', 'ajax_obj', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'smart_nonce' => wp_create_nonce( 'myajax-nonce' )  ) );

The unique nonce will generate and kept in that Global JavaScript object for every user. Nonce is WordPress security tokens that help us to protect from malicious attack. We almost done ajax initialization in WordPress.

jQuery WordPress Ajax Request:

Now we need to write jQuery script to make Ajax request to WordPress when user want to login or register. So every time user tries to login from WordPress frontend we need to get his/her credentials and pass it server via Ajax request to check he/she is valid user.

Here is my user registration jQuery Ajax script:

$(document).on('click','#register_btn',function(){
	register();
});
	
function register(){
	$('#register_btn').button('loading');
	jQuery.post(
		ajax_obj.ajax_url, 
	    {
	        'action': 'uregister',
	        'username' : $('#username').val(),
	        'email' : $('#remail').val(),
	        nonce : ajax_obj.smart_nonce
	    }, 
	    function(response){
	    	$('#register_btn').button('reset');
	        data = jQuery.parseJSON(response);
	        if( data.flag == true ){
	        	$('#registration_fail').show();
	        	$('#registration_fail').removeClass('response_error').addClass('response_success');
				$('#registration_fail').html(data.msg);
				$('#registration-span').hide();
		    }else{
				$('#registration_fail').show();
				$('#registration_fail').removeClass('response_success').addClass('response_error');
				$('#registration_fail').html(data.msg);
			}
	    }
	);
} 

Here is my user login jQuery Ajax script:

$(document).on('click','#login_btn',function(){
login();
});

function login(){
	$('#login_btn').button('loading');
	jQuery.post(
		ajax_obj.ajax_url, 
	    {
	        'action': 'login',
	        'data':   'foobarid',
	        'username' : $('#login_username').val(),
	        'password' : $('#password').val(),
	        nonce : ajax_obj.smart_nonce
	    }, 
	    function(response){
	        data = jQuery.parseJSON(response);
	        if( data.flag == true ){
		    location.reload();
		 }else{
		    $('#login_btn').button('reset');
		    $('#login_fail').show();	
		 }
	    }
	);
}

Here is my user forget password jQuery Ajax script:

$(document).on('click','#reset_btn',function(){
forget_password();
});

function forget_password(){
	$('#reset_btn').button('loading');
	jQuery.post(
		ajax_obj.ajax_url, 
	    {
	        'action': 'ureset_password',
	        'email' : $('#femail').val(),
	        nonce : ajax_obj.smart_nonce
	    }, 
	    function(response){
	    	$('#reset_btn').button('reset');
	        data = jQuery.parseJSON(response);
	        if( data.flag == true ){
	        	$('#reset_fail').show();
	        	$('#reset_fail').removeClass('response_error').addClass('response_success');
			$('#reset_fail').html(data.msg);
		 }else{
			$('#reset_fail').show();
			$('#reset_fail').removeClass('response_success').addClass('response_error');
			$('#reset_fail').html(data.msg);
		}
	    }
	);
}

WordPress Frontend Ajax login PHP Script:

Here comes PHP part that will handle Ajax request made from Frontend using jQuery. To handle Ajax request made from frontend we must register hook to handle that.
Register WordPress hook for user registration.

add_action('wp_ajax_uregister', 'uregister');
add_action('wp_ajax_nopriv_uregister', 'uregister');

Here comes user registration hook function.

function uregister() {

	$nonce = $_POST['nonce'];
	if ( ! wp_verify_nonce( $nonce, 'myajax-nonce' ) )
	die ( 'Invalid Request!');
	
	$data = array();
	$user_email = $_POST['email'];
	$user_name = $_POST['username'];
	$user_id = username_exists( $user_name );
	
	if ( $user_id) $user_name = ieb_wpUniqueUser($email);
	
	if ( !$user_id and email_exists($user_email) == false ) {
		$random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
		$user_id = wp_create_user( $user_name, $random_password, $user_email );
		//SendWelcomeEmail( $user_id, $random_password );
		$data['flag'] = true;
		$data['msg'] = "Your account is created, Please login to your email <strong>$user_email</strong> for login details.<br/><br/> <a href='javascript:;' class='signin-tab'>Click here to login</a>";
	} else {
		$data['flag'] = false;
		$data['msg'] = "Email already exists. Please <a href='javascript:;' class='signin-tab'>login</a> using $user_email";
	}
	echo json_encode($data);
	die();
}

WordPress Frontend Ajax User Login Script:

add_action('wp_ajax_login',        'login');
add_action('wp_ajax_nopriv_login', 'login');

function login() {
	
	$nonce = $_POST['nonce'];
	if ( ! wp_verify_nonce( $nonce, 'myajax-nonce' ) )
	die ( 'Invalid Request!');


	$creds = array();
	$data = array();
	$creds['user_login'] = $_POST['username'];
	$creds['user_password'] = $_POST['password'];
	$creds['remember'] = false;
	$user = wp_signon( $creds, false );
	if ( is_wp_error($user) ){
		$data['flag'] = false;
		$data['msg'] = $user->get_error_message();
	}else{
		$data['flag'] = true;
		$data['msg'] = "Login Successful. Please wait...";
	}
	echo json_encode($data);
	die();
}

WordPress Frontend Ajax User Forget Password Script:

add_action('wp_ajax_ureset_password', 'ureset_password');
add_action('wp_ajax_nopriv_ureset_password', 'ureset_password');
function ureset_password() {
	
	$nonce = $_POST['nonce'];
	if ( ! wp_verify_nonce( $nonce, 'myajax-nonce' ) )
	die ( 'Invalid Request!');
	
	$data = array();
	$user_email = $_POST['email'];
	$user = get_user_by( 'email', $user_email );
	$user_id = $user->ID;
	if(!empty($user_id)){
		$random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
		wp_set_password( $random_password, $user_id );
		//SendWelcomeEmail( $user_id, $random_password );
		$data['flag'] = false;
		$data['msg'] = "We sent you an email with reset instructions!!";
	}else{
		$data['flag'] = false;
		$data['msg'] = "Email not exists, Please enter valid email!!";
	}
	echo json_encode($data);
	die();
}

I had not covered the mailing part, Please take care mailing part youself.

.

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!