This tutorial will show you how you can check username availability using Codeigniter, AJAX and MySQL. Sometimes we need to check username availability instantly before a user presses the submit button after filling a long-sized signup form. In this case we can use AJAX technique with any server side technologies like PHP, Codeigniter, Servlet, Struts, JSF, Spring etc. for checking whether the input username is avaialable for creating new user account or it has already been taken by someone else. So if we give instant result to the user for username availability then sometimes it makes more sensible than while pressing the submit button and goes top of the signup form to rectify the username input field if input username is not available. So after finishing this example “username check availability using Codeigniter, AJAX and MySQL” you will be able to apply the same logic to any server side technologies.

If you need similar example using PHP and Servlet then read here Username availability check using PHP, AJAX and MySQL and Username availability check using Servlet, AJAX and MySQL respectively.

This example uses JavaScript event onblur for checking user availability. Onblur means when focus is out of a particular object such as inputbox, textarea etc., then an event occurrs, i.e., we need to perform some activities.

Prerequisites

Knowledge of PHP & Codeigniter
Knowledge of MySQL or any other database
Knowledge of JavaScript or jQuery framework
Codeigniter 3

jQuery libraries

jquery-3.3.1.min.js  -> https://jquery.com/download/
jquery-migrate-1.4.1.js -> https://jquery.com/download/
jquery-ui-1.10.3.custom.min.js -> https://osdn.net/projects/sfnet_javanautics/downloads/js/jquery-ui-1.10.3.custom.min.js/

Now we will implement the example using following steps

First and formost thing is to create a database table in MySQL because we will check the availability of the username in the database. So create below table in the MySQL table

CREATE TABLE `user` (
	`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
	`login_username` varchar(100) NOT NULL,
	`login_password` varchar(255) NOT NULL,
	`last_login` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
	PRIMARY KEY (`user_id`),
	UNIQUE KEY `login_email_UNIQUE` (`login_username`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;

In order to test the example is really working we need some data in the above table, so insert some data in the above table

insert into 
`user`(`user_id`,`login_username`,`login_password`,`last_login`) 
	values 
(1,'user1','$2a$08$S5IfrpOVOvFbbOSOmZpjsO5N9PXgEerTloK','2014-07-19 19:18:30'),
(14,'user2','$2a$08$v1kJflweCK3FOcoAsmYAUCMxFa5Shh7c2','2013-11-17 19:22:46');

Please read how to configure Codeigniter with Netbeans before continuing forwards

Now create assets_helper.php file under the directory <project directory>/application/helpers/ in order to load the static resources such as js, css and images because you cannot directly access such files in the web page.

<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

function assets_url() {
	return base_url();
}

/* End of file assets_helper.php */
/* Location: ./application/helpers/assets_helper.php */

Now auto-load database library and few helper functions along with our custom assets_helper.php file in the following way. It is always better to auto-load such things, which are required to load only once and applicable for application wide use. Notice how we auto-load assets_helper.php file in helper section. We have removed “_helper.php” from the name of the file because the helper file’s names are given with prefix “_helper” but need not to mention when we auto-load. Edit the appropriate sections in the file <project directory>/application/config/autoload.php

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url', 'file', 'text', 'form', 'assets');

Now configure the database section in order to connect with MySQL database for performing database activities in the file <project directory>/application/config/database.php. Please replace below values with your own values.

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'ci_post';
$db['default']['dbdriver'] = 'mysqli';

Now update the default controller in <project directory>/application/config/routes.php in order to access the default controller when the application starts up.

$route['default_controller'] = "Auth";

Create below Auth controller under <project directory>/application/controllers directory with below source code. In the below controller we load the model class in the constructor, which we will create in next step. We load the view in the index() function in order to show the default view to end user on application start up. We have created another function get_username_availability() to call on JavaScript’s onblur event to check username availability.

<?php

if (!defined('BASEPATH'))
exit('No direct script access allowed');

/**
* Description of auth
*
* @author https://www.roytuts.com
*/
class Auth extends CI_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('auth_model');
	}

	public function index() {
		$this->load->view('auth');
	}

	function get_username_availability() {
		if (isset($_POST['username'])) {
			$username = $_POST['username'];
			$results = $this->auth_model->get_username($username);
			if ($results === TRUE) {
				echo '<span style="color:red;">Username unavailable</span>';
			} else {
				echo '<span style="color:green;">Username available</span>';
			}
		} else {
			echo '<span style="color:red;">Username is required field.</span>';
		}
	}

}

/* End of file auth.php */
/* Location: ./application/controllers/auth.php */

Create below model class under <project directory>/application/models in order to perform database operations in MySQL. Notice the below model class has been loaded into the constructor of the above controller class. Here we have defined one function to return true or false based on the given username’s availability in the database.

<?php

if (!defined('BASEPATH'))
exit('No direct script access allowed');

/**
* Description of auth_model
*
* @author https://www.roytuts.com
*/

class Auth_model extends CI_Model {

	private $user = 'user';

	function get_username($username) {
		$this->db->where('login_username', $username);
		$this->db->limit(1);
		$query = $this->db->get($this->user);

		if ($query->num_rows() == 1) {
			return TRUE;
		}
		
		return FALSE;
	}

}

/* End of file auth_model.php */
/* Location: ./application/models/auth_model.php */

Create a view file auth.php with the following source code under <project directory>/application/vies/. Please look carefully at the URL which is used in AJAX request/response, I did not use index.php. If you want to remove index.php then you can have a look at the tutorial How to remove index.php in Codeigniter. If you do not want to remove index.php from URL then you do not need to read the tutorial related to removing index.php from URL.

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Check username availability using jQuery, AJAX</title>
	<script src="<?php echo assets_url(); ?>assets/js/jquery-3.3.1.min.js"></script>
	<script src="<?php echo assets_url(); ?>assets/js/jquery-migrate-1.4.1.js"></script>
	<script src="<?php echo assets_url(); ?>assets/js/jquery-ui-1.10.3-custom.min.js"></script>
</head>
<body>
	<div style="margin: 10px 0 0 10px;width: 600px">
		<h3>Codeigniter username availability check</h3>

		<form id="signupform" style="padding: 10px;">
			<fieldset>
				<legend>Check username</legend>
				<div>
					<label>Username</label><br/>
					<input type="text" name="username" id="username"/>
					<div id="msg"></div>
				</div>
			</fieldset>
		</form>
	</div>
</body>
</html>

<!-- below jquery things triggered on onblur event and checks the username availability in the database -->
<script type="text/javascript">
	$(document).ready(function() {
		$("#username").live("blur", function(e) {
			$('#msg').hide();
			if ($('#username').val() == null || $('#username').val() == "") {
				$('#msg').show();
				$("#msg").html("Username is required field.").css("color", "red");
			} else {
				$.ajax({
					type: "POST",
					url: "http://localhost/ci_post/auth/get_username_availability",
					data: $('#signupform').serialize(),
					dataType: "html",
					cache: false,
					success: function(msg) {
						$('#msg').show();
						$("#msg").html(msg);
					},
					error: function(jqXHR, textStatus, errorThrown) {
						$('#msg').show();
						$("#msg").html(textStatus + " " + errorThrown);
					}
				});
			}
		});
	});
</script>

Put all downloaded jQuery libraries under <project directory>/assets/js directory.

Run the application, you will get below output in the browser

username availability check codeigniter

If you click on input box and tab out then you will see below screen because you must input something

username availability check codeigniter

If you give input like ‘abc’ and tab out then you see below output because username does not exist

username availability check codeigniter

If you input ‘user1’ and tab out then you see below output because username already exists

username availability check codeigniter

Thanks for reading. Please feel free to comment using below form if you have any query.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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