About Lesson
Creating a simple tutorial on login with 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 `login_info` ( `id` int(10) NOT NULL, `name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `mobile_number` varchar(50) 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 `login_info` ADD PRIMARY KEY (`id`);
Step 4: Model
Create a model to interact with the database.
<?php
namespace App\Models\login;
use CodeIgniter\Model;
use CodeIgniter\Database\ConnectionInterface;
class LoginModel extends Model {
protected $db;
public function __construct(ConnectionInterface &$db) {
$this->db =& $db;
$this->table = 'login_info';
}
public function addEntry($data) {
$this->db
->table($this->table)
->insert($data);
return $this->db->insertID();
}
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();
}
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 getNumRows($where) {
return $this->db
->table($this->table)
->where($where)
->get()
->getNumRows();
}
}
Step 5: Controller
Create a controller for handling login requests.
<?php
namespace App\Controllers\login;
use App\Controllers\BaseController;
use App\Models\login\LoginModel;
class Login extends BaseController {
public function __construct() {
$db = db_connect();
$this->session = ConfigServices::session();
$this->login = new LoginModel($db);
$this->ip_address = $_SERVER['REMOTE_ADDR'];
$this->datetime = date("Y-m-d H:i:s");
}
public function index() {
$this->login();
}
public function login() {
$data = [];
$data ['content_title'] = 'Login';
echo view('login/login', $data);
}
public function authenticate() {
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
$where = [
'email' => $email,
'password' => md5($password),
];
$result = $this->login->getEntry($where);
if($result) {
$data = [
'login_id' => $result->id,
'login_email' => $result->email,
'login_name' => $result->name,
'login_mobile_number' => $result->mobile_number,
'user_status' => $result->status,
'login_status' => TRUE,
];
$this->session->set($data);
$json = [
'status' => true,
'message' => showSuccessMessage("Logged in successfully"),
'location' => base_url('myaccount'),
];
} else {
$json = [
'status' => false,
'message' => showDangerMessage("Entered email address does not exists. Please try again"),
];
}
echo json_encode($json);
}
}
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="row">
<div class="col-sm-3">
</div>
<div class="col-sm-6">
<div class="message"></div>
<form id="form-login" method="post" autocomplete="off">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
</div>
<div class="form-group">
<button type="submit" id="btn-login" class="btn btn-success">Login</button>
<a href="<?php echo base_url("signup"); ?>" class="btn btn-info">Go to Signup</a>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#form-login").on("submit", function(e) {
e.preventDefault();
let data = $(this).serialize();
$.post('<?php echo base_url("login/authenticate"); ?>', data, function(result) {
$(".message").html(result.message);
if(result.status) {
window.location.replace(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('/', 'login\Login::index');
$routes->post('authenticate', 'login\Login::authenticate');
});
Step 8: Test
Run in command prompt: php spark serve
Visit http://localhost:8080/login
in your browser and test the login form.