In this comprehensive Codeigniter 4 tutorial, you will learn how to retrieve stored data or the collection of data from the MySQL database with the help of AJAX.
Create Codeigniter Project
donwload codeigniter 4 via composer command
composer create-project codeigniter4/appstarter
Create User data Table in DB
import the below code in your phpmyadmin to create user table in your database
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL COMMENT 'Primary Key',
`name` varchar(100) NOT NULL COMMENT 'name',
`email` varchar(100) NOT NULL COMMENT 'email',
`mobile` varchar(100) NOT NULL COMMENT 'mobile'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='user collection';
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `mobile`) VALUES
(1, 'Elizabeth', ' alfreda1@hotmail.com', ' 803-332-6744'),
(2, 'Maria Nave', ' immanuel@gmail.com', ' 743-230-1388'),
(3, 'Elvia Nunez', ' alvena1@gmail.com', ' 307-616-3700'),
(4, 'Lucille Saucedo', ' valentin@gmail.com', ' 223-414-1964'),
(5, 'Billy Jankowski', ' reva@gmail.com', ' 546-398-7344');
Connect Application to Database
Open app/Config/Database.php and add your database username , password and Database name .
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'db_username',
'password' => 'db_password',
'database' => 'db_name',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'development'),
'cacheOn' => false,
'cacheDir' => '',
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
Creaste Model File
Create app/Models/User.php model in your application
<?php
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
class User extends Model
{
protected $table = 'users';
protected $allowedFields = [
'name',
'email',
'mobile'
];
public function fetchRecords($id = false) {
if($id === false) {
return $this->findAll();
} else {
return $this->getWhere(['id' => $id]);
}
}
}
Create Controller file
Create app/Controllers/UserController.php file in your application and import the User model
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\User;
class UserController extends BaseController {
public function index(){
$data['name'] = 'Elizabeth';
$data['content'] = 'output';
return view('index', $data);
}
public function getRecords(){
$userModel = new User();
$data['users'] = $userModel->fetchRecords();
echo view('output', $data);
}
}
Create Route
you can add routes of your existing controller to navigate on the brower directly by url. open the fill app/Config/Routes.php and create routes
/*
* --------------------------------------------------------------------
* Route Definitions
* --------------------------------------------------------------------
*/
$routes->get('/', 'UserController::index');
$routes->get('/get-records', 'UserController::getRecords');
Create View File
Create the view and call the ajax function to get the data from php file. Update code in app/Views/index.php file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Codeigniter 4 Ajax Retreive Data Example</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.container {
max-width: 500px
}
</style>
</head>
<body>
<div class="container mt-5">
<div id="results"> </div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
reloadTable()
function reloadTable() {
$.ajax({
url: "<?php echo site_url('UserController/getRecords'); ?>",
beforeSend: function (res) {
$('#results').html('Fetching ...');
},
success: function (data) {
$('#results').html(data);
}
})
}
</script>
</div>
</body>
</html>
Create the app/Views/output.php file. and show the data in actual index.php file
<?php foreach($users as $data) { ?>
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title"><?php echo $data['name']; ?></h5>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><?php echo $data['id']; ?></li>
<li class="list-group-item"><?php echo $data['email']; ?></li>
<li class="list-group-item"><?php echo $data['mobile']; ?></li>
</ul>
</div>
<?php } ?>
Run App in Browser
use the PHP artisan command to run the application
php spark serve
http://localhost:8080