CodeIgniter 4 AJAX Tutorial
About Lesson

Creating a simple tutorial on login with a mobile number and OTP using AJAX using CodeIgniter 4 involves several steps, including setting up the database, creating the controller, model, and view, and implementing AJAX for asynchronous communication. Here’s a step-by-step guide:

 

Step 1: Setup CodeIgniter 4 Project

Make sure you have CodeIgniter 4 installed. If not, you can follow the official documentation to install it.

 

Step 2: Database Configuration

Configure your database settings in App/Config/Database.php.

public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'infovistar_ci4_db',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
];

 

Step 3: Create Database Table

Create a table for users in your database.

CREATE TABLE `user_info` (
  `id` int(10) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `mobile_number` varchar(50) NOT NULL, 
`otp` varchar(255) NOT NULL, `ip_address` varchar(255) NOT NULL, `created_at` datetime NOT NULL, `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `status` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

ALTER TABLE `user_info`
  ADD PRIMARY KEY (`id`);

 

Step 4: Model

Create a model to interact with the database.

<?php
namespace App\Models\user;

use CodeIgniter\Model;
use CodeIgniter\Database\ConnectionInterface;

class UserModel extends Model {

protected $db;

public function __construct(ConnectionInterface &$db) {
$this->db =& $db;
$this->table = 'user_info';
}

public function addEntry($data) {
$this->db->table($this->table)
->insert($data);

return $this->db->insertID();
}

public function getEntry($where) {
return $this->db->table($this->table)
->where($where)
->get()
->getRow();
}

public function getEntryList($where = 0) {
if($where) {
return $this->db->table($this->table)
->where($where)
->get()
->getResult();
} else {
return $this->db->table($this->table)
->get()
->getResult();
}

}

public function updateEntry($where, $data) {
return $this->db->table($this->table)
->where($where)
->set($data)
->update();
}

public function deleteEntry($where) {
return $this->db->table($this->table)
->where($where)
->delete();
}

}

 

Step 5: Controller

Create a controller for handling login requests.

<?php
namespace App\Controllers\login;

use App\Controllers\BaseController;
use App\Models\user\UserModel;

class Login extends BaseController {

public function __construct() {
$db = db_connect();
$this->user = new UserModel($db);
}

public function index() {
$this->login();
}

public function login() {
$data = [];
$data ['content_title'] = "Login with Mobile Number and OTP";
$data ['main_content'] = "login/login";
echo view('innerpages/template', $data);
}

public function send_otp() {
$mobile_number = $this->request->getPost('mobile_number');
if($mobile_number) {
$where = [
"mobile_number" => $mobile_number,
];
$result = $this->user->getEntry($where);
$otp = $this->getOtp();
if($result) {
$data = [
'otp' => $otp,
'status' => '0',
];
$result = $this->user->updateEntry(['id' => $result->id], $data);
} else {
$data = [
"mobile_number" => $mobile_number,
'otp' => $otp,
'status' => '0',
];
$result = $this->user->addEntry($data);
}
if($result) {
$this->sendSMS("148397", $otp.'|', str_replace("+91", "", $mobile_number));
$json = [
'message' => 'OTP has been sent successfully',
'status' => true,
];
} else {
$json = [
'message' => 'Something went wrong. Please try again',
'status' => false,
];
}
} else {
$json = [
'message' => 'Enter your Mobile Number',
'status' => false,
];
}
echo json_encode($json);
}

public function verify_otp() {
$mobile_number = $this->request->getPost('mobile_number');
$otp = $this->request->getPost('otp');

$where = [
"mobile_number" => $mobile_number,
"otp" => $otp,
];
$result = $this->user->getEntry($where);
if($result) {
$data = [
'status' => '1',
];
$this->user->updateEntry(['id' => $result->id], $data);
$json = [
'message' => 'LoggedIn Successfully',
'location' => base_url('crud/list'),
'status' => true,
];
} else {
$json = [
'message' => 'Entered OTP is not a valid',
'status' => false,
];
}
echo json_encode($json);
}

function getOtp() {
$otp = rand(1, 9);
$otp .= rand(0, 9);
$otp .= rand(0, 9);
$otp .= rand(0, 9);
$otp .= rand(0, 9);
$otp .= rand(0, 9);
return $otp;
}

function sendSMS($message, $variables_values, $mobile_numbers) {
$url = 'https://www.fast2sms.com/dev/bulkV2';
$authorization = 'z015jdvEkGf2FRLYPu8ynTQ7MqecSDZAhUJgrm3Ai29MUhawp4XYzGbtS5Fr0uKWRVf';
$sender_id = 'CXSTCH';
$route = 'dlt';

$body = $url . '?authorization=' . $authorization . '&sender_id=' . $sender_id . '&message=' . $message . '&variables_values=' . urlencode($variables_values) . '&route=' . $route . '&numbers=' . $mobile_numbers;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);
if (curl_errno($ch)) {
// echo 'Error:' . curl_error($ch);
}
curl_close($ch);
}

}

 

Step 6: View

Create a view for the signup form.

<!DOCTYPE html>
<html lang="en">

<head>
<title><?php echo $content_title; ?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>

<body>
<div class="jumbotron text-center">
<h1>Welcome to Infovistar.in</h1>
<p>Login Example with AJAX</p>
</div>
<div class="container">
<div class="jumbotron">
<h1>Login with Mobile Number and OTP</h1>
<p>CodeIgniter 4.</p>
</div>
<div class="row">
<div class="col-sm-12 send-otp">
<form id="form-send-otp" method="post" autcomplete="off">
<div class="form-group">
<label>Mobile</label>
<input type="text" name="mobile_number" id="send_otp_mobile_number" class="form-control" placeholder="Enter mobile number" maxlength="10" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Send OTP</button>
</div>
</form>
</div>

<div class="col-sm-12 verify-otp" style="display: none;">
<form id="form-verify-otp" method="post" autcomplete="off">
<div class="form-group">
<label>Mobile</label>
<input type="text" name="mobile_number" id="verify_otp_mobile_number" class="form-control" placeholder="Enter mobile number" maxlength="10" readonly>
</div>
<div class="form-group">
<label>OTP</label>
<input type="text" name="otp" class="form-control" placeholder="Enter OTP" maxlength="6" minlength="6" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Verify OTP</button>
</div>
</form>
</div>
</div>
</div>
 
<script>
$(document).ready(function() {

$("body").on("submit", "#form-send-otp", function(e) {
e.preventDefault();
let data = $(this).serialize();
$.post('<?php echo base_url("login/send-otp") ?>', data, function(result) {
alert(result.message);
if(result.status) {
$("#verify_otp_mobile_number").val($("#send_otp_mobile_number").val());
$(".send-otp").hide();
$(".verify-otp").show();
}
}, 'json');
});

$("body").on("submit", "#form-verify-otp", function(e) {
e.preventDefault();
let data = $(this).serialize();
$.post('<?php echo base_url("login/verify-otp") ?>', data, function(result) {
alert(result.message);
if(result.status) {
window.location.href = result.location;
}
}, 'json');
});

});
</script>

 


</body>

</html>

 

Step 7: Routes

Configure a route to access the login page and handle the login request.

 
// Login Routes
$routes->group('login', function($routes) {
$routes->get('/', 'loginLogin::index');
$routes->post('send-otp', 'loginLogin::send-otp');
$routes->post('verify-otp', 'loginLogin::verify-otp');
});

 

Step 8: Test

Run in command prompt: php spark serve

Visit http://localhost:8080/login in your browser and test the login form.