AJAX Example with CodeIgniter 4 and MySQL – Check Username Availability

Here I am going to explain how to use AJAX with CodeIgniter 4 and MySQL to check the availability of username on key event. So instead of user waiting at the end of the input form and submitting the form, I am going to let user know immediately whether the username he/she is choosing is available or someone else has already taken. This way user does not have to come to the username input field after submitting the form.

So if you give instant result to the user for username availability then some time it makes more sense 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.

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

Related Posts:

Prerequisites

PHP 7.4.3, Codeigniter 4.0.4, MySQL 8.0.17/8.0.22

Project Directory

It’s assumed that you have setup PHP and CodeIgniter in Windows system.

Now I will create a project root directory called codeigniter-4-mysql-ajax-username-check anywhere in the system.

Now move all the directories and files from CodeIgniter framework into the project root directory.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

MySQL Table

For this example I am going to create and insert few sample data into the table user under roytuts 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;

insert into `user`(`user_id`,`login_username`,`login_password`,`last_login`) 
values (1,'user1','$2a$08$S5IfrpOVOvFbbOSOmZpjsO5N9PXgEerTloK','2021-01-04 19:18:30'),(2,'user2','$2a$08$v1kJflweCK3FOcoAsmYAUCMxFa5Shh7c2','2021-01-04 19:22:46');

Database Configuration

You need to setup database connection in order to fetch or write data to the table. The following configuration is done in the file app/Config/Database.php under the default group of database setting. Make sure you change or update the configuration according to yours. You can also setup your database using the .env file.

The main properties I have shown below and you can change according to your values:

...
'username' => 'root',
'password' => 'root',
'database' => 'roytuts',
...
'charset'  => 'utf8mb4',
'DBCollat' => 'utf8mb4_unicode_ci',
...

Model

You need a model class to perform database activities, for example, to check the username availability I am using below model class. The below model class is written into app/Models/UserModel.php file.

In CodeIgniter you can choose two ways of modeling your data – using CodeIgniter’s model and using entity class. I am using CodeIgniter’s model to create my own model that extends CodeIgniter’s model class. They come out of the box with helper methods for much of the standard ways you would need to interact with a database table, including finding records, updating records, deleting records, and more.

I am creating my own function in the model class to check data exist or not in the table for the input data.

<?php

namespace App\Models;
use CodeIgniter\Model;

class UserModel extends Model {

	protected $table = 'user';
	
	function get_username($username) {
		$sql = "SELECT * FROM user WHERE login_username = ? LIMIT 1";
		$query = $this->db->query($sql, [$username]);
		
		$row = $query->getRow();
		
		if ($row) {
			return true;
		}
		
		return false;
	}
	
}

Using the standard query() method I am executing my own query and finally returning true or false based on the getRow() method that fetches a row for the given username.

I have used here a place holder (?), for where clause, which will be actually replaced by the second parameter in the query() function. This is called query binding.

Controller

The following controller (app/Controllers/User.php) defines the functions for handling user’s request/response and calling the appropriate views and interact with database table to perform the required activities.

<?php

namespace App\Controllers;
use App\Models\UserModel;

class User extends BaseController {
	
	public function __construct() {
		helper(['form', 'url']);
	}
	
	public function index()	{
		return view('username');
	}

	public function check_username_availability() {
		$requestBody = json_decode($this->request->getBody());

		$username = $requestBody->username;
			
		if ('post' === $this->request->getMethod() && $username) {
			$model = new UserModel();
			
			$result = $model->get_username($username);
			
			if ($result === true) {
				echo '<span style="color:red;">Username already taken</span>';
			} else {
				echo '<span style="color:green;">Username Available</span>';
			}
		} else {
			echo '<span style="color:red;">You must enter username</span>';
		}
	}
	
}

In the above class I have defined index() function that simply returns the view page.

The other function check_username_availability() actually gets called on AJAX request. In this function I received the request payload using the CodeIgniter 4’s request API getBody() function and finally using the json_decode() function I am retrieving the actual parameter from the JSON body.

Next I am checking against the database table whether the input username already exists or not and accordingly return the message.

View File

You need to display your data onto a view file. Therefore you will need to create a view file (for example, username.php) under app/Views folder.

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Check username availability using CodeIgniter 4, MySQL, jQuery, AJAX</title>
	<meta name="description" content="The small framework with powerful features">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>
	<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" crossorigin="anonymous"></script>
</head>
<body>
	<div style="margin: 10px 0 0 10px;width: 600px">
		<h3>Codeigniter 4, MySQL, AJAX - Username Availability Check</h3>
		<div style="padding: 10px;">
			<fieldset>
				<legend>Check Username Availability</legend>
				<div>
					<label>Username</label><br/>
					<input type="text" name="username" id="username"/>
					<div id="msg"></div>
				</div>
			</fieldset>
		</div>
	</div>
	
	<!-- 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 a required field.").css("color", "red");
				} else {
					$.ajax({
						type: 'post',
						url: "<?= site_url('check-username-availability')//site_url('user/check_username_availability') ?>",
						data: JSON.stringify({username: $('#username').val()}),
						contentType: 'application/json; charset=utf-8',
						dataType: 'html',
						cache: false,
						beforeSend: function (f) {
							$('#msg').show();
							$('#msg').html('Checking...');
						},
						success: function(msg) {
							$('#msg').show();
							$("#msg").html(msg);
						},
						error: function(jqXHR, textStatus, errorThrown) {
							$('#msg').show();
							$("#msg").html(textStatus + " " + errorThrown);
						}
					});
				}
			});
		});
	</script>
</body>
</html>

I am using AJAX using jQuery library and I am loading the jQuery library from CDN (Content Delivery Network). I am also using jQuery UI for capturing UI (User Interface) event.

In the ajax({...}) function I am passing the required parameters, such as, http method type, url, contentType that will be sent to the server, dataType that is captured as a response from the server, data that has to be sent to the server. JSON.stringify() is used to convert data into JSON format.

The beforeSend() function is actually used to fire the event what you want before sending data to the server. In this example it will show you the message Checking... on each input letter you press.

The success() function will show you the response from the server if there is no error on the server side.

The error() function will show you the server error.

Route Configuration

You also need to configure route to point to your own controller file instead of the default controller that comes with the framework.

Search for the line $routes->setDefaultController('Home'); and replace it by $routes->setDefaultController('User');.

Search for the line $routes->get('/', 'Home::index'); and replace it by your controller name, for this example, $routes->get('/', 'User::index');.

These route configurations are done on the file app/Config/Routes.php.

Now I have defined another route for this example. The default URL you will use for the AJAX call is user/check_username_availability but I do not want to use this URL, so I have configured a route in the Routes.php file. So I am going to use URL check-username-availability and for this URL I have configured a route as shown below:

$routes->post('/check-username-availability', 'User::check_username_availability');

Testing the Application

I am not going to use any external server but CLI command to run the application. Make sure you start the MySQL database server before you start your application. If you want to use external server to run your application you can use. Execute the following command on your project root directory to run your application.

php spark serve

Your application will be running on localhost and port 8080.

The URL http://localhost:8080/ will show you the following page on the browser.

ajax with codeigniter 4 to check username availability

When username is available, i.e., the input username which you want has not been taken by anyone else then you will see the below output as shown in the image.

ajax with codeigniter 4 and mysql to check username availability

If the username which you want has been taken by someone else then you will see the following message.

how to use ajax with codeigniter 4

That’s all about how to use AJAX with CodeIgniter 4 to check a record in MySQL database on jQuery/JavaScript’s input event.

Source Code

Download

Leave a Reply

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