Check username availability in database using Ajax and Codeigniter

Today I'm going to do a small tutorial based on Ajax and Codeigniter. It's a kind of validation tutorial for username that we see always when we register in web sites. I think you have seen a real time validation for a entered username is included in many online registration forms. The most used technology is Ajax. Ajax is used for real time tasks in web design, without reloading the web page. Here I'm not going to create a whole form and submit data. What I will be doing is just explain how to check a username whether it is already available in a database or not. If you want you can do it for email also. 

First download Codeigniter and do the basic configurations as I did in my all Codeigniter tutorials.

Project folder => AjaxUsernameCheck
Base URL => $config['base_url'] = 'http://localhost/AjaxUsernameCheck/
Database name => pagination (I will use a previous database used by me. You can create a db with a suitable name)
Database table name => users
Autoload libraries => database
Default Controller => Search

Now I will create the view first using Bootstrap framework. In the head section of view, I use several links for this article. 


1 - Bootstrap CDN to link Bootstrap styles
2 - Ajax CDN by Google for real time tasks
3 - Font Awesome CDN to include icons in the design
4 - Roboto font link to change the font to Roboto

View - check.php

For now, I removed the ajax script from the view. I will explain it later separately.

<!DOCTYPE html>
<html>
<head>
<title>Tutorial</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<style type="text/css">
body {
font-family: 'Roboto', sans-serif;
}
label {
font-size: 16px;
}
#heading {
margin-top: 50px; 
margin-bottom: 50px;
text-align: center;
}
</style>
</head>
<body>
<div class="col-lg-12">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<br>
<h2 id="heading">Check Username availability with Ajax and Codeigniter</h2>
<br>
<label for="username">Enter Username</label>
<input type="text" name="username" id="username" class="form-control">
<br>
<span id="username_result"></span>
<br><br>
<label for="password">Enter Password</label>
<input type="text" name="password" id="password" class="form-control">
</div>
<div class="col-lg-3"></div>
</div>
</body>
</html>

Explanation:

<span id="username_result"></span> - To display error/success messages

Note : The input fields should not be the same. You can change it according to the database fields included in your database.

We are going to create the model now for fetching username.


Model - Search_model.php


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

class Search_model extends CI_Model {

public function getUsername($username)
{
$this->db->where('username' , $username);
$query = $this->db->get('users');

if($query->num_rows()>0){
return true;
}
else {
return false;
}
}
}

Explanation :

Here getUsername function is getting the matching username to the entered username in the input field, from database. I passed a parameter called $username to compare it with the database result. If there's a username already in the database, function will return true and otherwise returns false.

Now we need to create the controller to load views and include logic for username checking.

Controller - Search.php


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

class Search extends CI_Controller {

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

public function checkUsername()
{
$this->load->model('Search_model');
if($this->Search_model->getUsername($_POST['username'])){
echo '<label class="text-danger"><span><i class="fa fa-times" aria-hidden="true">
</i> This user is already registered</span></label>';
}
else {
echo '<label class="text-success"><span><i class="fa fa-check-circle-o" aria-hidden="true"></i> Username is available</span></label>';
}
}

}

Explanation :

Here checkUsername function first load the model. Then call for the model function getUsername and get the username by POST method. After the model function is called , the controller will execute the rest according to the result passed from model to the controller. Ajax back-end part is still missing. Don't worry about it. Without it, this is not working as we thought. Controller is simply prints the message to the view according to the logic executed with Ajax and Codeigniter.

Ajax , jQuery script


This is the most important part of this article. Do not miss this! 
Add the below code just before the ending HTML body tag of the view; check.php.

<script type="text/javascript">
$(document).ready(function(){
$('#username').change(function(){
var username = $('#username').val();
if(username != ''){
$.ajax({
url: "<?php echo base_url(); ?>Search/checkUsername",
method: "POST",
data: {username:username},
success: function(data){
$('#username_result').html(data);
}
});
}
});
});
</script>

This is a Javascript code to get the real time validation messages.

Explanation : 

$('#username').change(function(){
Change function for username; #username means the id of username input field

var username = $('#username').val();
Get the value of input username field and store it in a variable called username.

if(username != ''){}
Check whether username input field is not a blank. If it is not empty, then the Ajax request will be executed.

$.ajax({  -  Beginning of Ajax request.

url: "<?php echo base_url(); ?>Search/checkUsername"
URL for the controller function which is needed to be called to get the results. A request is sent to this URL.

method: "POST"  -  Method is taken as POST since we are using POST method to send request.

data: {username:username}  -  Sends the username data to the server.

success: function(data){}  
Success callback function to be called after a request is successfully sent. This function will receive data from server. According to the logic built with CI controller and model, this function will receive a message telling about username availability.

$('#username_result').html(data)
If data is received from the server(message) it should be displayed. Previously we reserved a place for messages in the view file. It has an ID also. Here, this line says to display the result message withing the section having the id called username_result under the HTML method.

Now our jQuery code is ready to work with a Ajax request! Save all the files and try it in your web browser. I have uploaded a short demo video to understand the process.
Admin Semoga Informasi Yang Diberikan Melalui Web Ini Dapat Bermanfaat Bagi Saudara/i

No comments for "Check username availability in database using Ajax and Codeigniter"