Introduction

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 available 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.

You may also read:

This example uses JavaScript event on input event for checking user availability.

Prerequisites

Apache 2.4, CodeIgniter 3.1.10, PHP 7.3.5, MySQL 8.0.17

Creating Project Directory

It’s assumed that you have setup Apache 2.4, PHP 7.3.5 and Codeigniter 3.1.10 in Windows system.

Now we will create a project root directory called codeIgniter-ajax-mysql-username-availability-check under the Apache server’s htdocs folder.

Now move all the directories and files from CodeIgniter 3.1.10 framework into codeIgniter-ajax-mysql-username-availability-check directory.

We may not mention the project root directory in subsequent sections and we will assume that we are talking with respect to the project’s root directory.

Creating MySQL Table

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

So create a table user under database roytuts in the MySQL server with the below structure.

CREATE TABLE `user` (
	`user_id` int 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=2 DEFAULT CHARSET=utf8mb4;

Dumping Data

We need to insert some data in order to complete the test that checks whether the functionality is really working as expected.

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

Autoload Configuration

Now auto-load database library and a helper function. It is always better to auto-load such things, which are required to load only once and applicable for application wide use.

Edit the appropriate sections in the file /application/config/autoload.php.

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

Database Configuration

Now configure the database section in order to connect with MySQL database for performing database activities.

Edit the file application/config/database.php.

Replace below values with your own values.

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

Creating Controller Class

Create a file called UsernameCheck.php under application/controllers with the below source code. This controller class handles request and response for the clients.

In the below controller we load the model class in the constructor, which we will create in next step. We give an alias for model class to shorten the name.

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 on input event to check username availability.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class UsernameCheck extends CI_Controller {

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

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

	function get_username_availability() {
		if (isset($_POST['username'])) {
			$username = $_POST['username'];
			$results = $this->um->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>';
		}
	}
}

Creating Model Class

Create below model class UsernameCheck_Model under application/models folder 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 UsernameCheck_Model
*
* @author https://www.roytuts.com
*/

class UsernameCheck_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;
	}

}

Creating View

Create a view file username.php with the following source code under application/views folder.

We are using the jQuery libraries from CDN.

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Check username availability using CodeIgniter, jQuery, AJAX</title>
	<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
	<script src="https://code.jquery.com/jquery-migrate-3.1.0.min.js"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.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 on input event and checks the username availability in the database -->
<script type="text/javascript">
	$(document).ready(function() {
		$("#username").on("input", 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/codeIgniter-ajax-mysql-username-availability-check/index.php/usernamecheck/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>

Configuring Route

We need to put default controller in order to access the home page without typing controller name in the browser.

$route['default_controller'] = 'usernamecheck';

Testing the Application

Run the application and hit the URL http://localhost/codeIgniter-ajax-mysql-username-availability-check/index.php, 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

Source Code

You can download source code.

Thanks for reading.

Tags:

1 thought on “Username availability check using Codeigniter, AJAX and MySQL

Leave a Reply

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