CodeIgniter 4 AJAX Tutorial – Fetch Data from Database
Ajax means Asynchronous JavaScript And XML, and it is a popularly known web development technique. This web technology is used on the client-side to develop asynchronous web applications.
This technology propels the web development process and allows you to send and get the data from a web server asynchronously without interfering with the display and behavior of the existing web page.
Read more: Build a CRUD Application in Codeigniter with Bootstrap.
Codeigniter AJAX Example
Let us understand what and how we are trying to achieve in this tutorial.
We will create a basic CRUD application using the Composer package. Thereafter, we will make the consensus between CI and MySQL. By following the MVC pattern, we ill create a Model. It’s an archetype of database values. Within which we define a simple function that gets all the records from the database.
We will gradually connect all the parts and maintain the concurrent impulse of AJAX web development techniques. Then, we will create two functions inside the Controller and load the view and fetch the records using Model simultaneously.
With gravitas, we will create views and load all the data inside the view and display on the user screen using AJAX in Codeigniter 4.
Table of Contents
Install Codeigniter 4
You must have a composer package installed on your device to install the Codeigniter application.
composer create-project codeigniter4/appstarter
After installing the app, change the name of the folder such as codeigniter-ajax-crud.
Next, get inside the app folder:
cd codeigniter-ajax-crud
You can also manually download the Codeigniter application.
Facilitate Codeigniter Errors
We have to enable the the error reporting by setting display_errors
to 1 instead of 0 in app/Config/Boot/development.php and app/Config/Boot/production.php files.
ini_set('display_errors', '1');
Connect Database
To maintain the ongoing impulse, you can execute the SQL query from PHPMyAdmin to create the users table.
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
name varchar(100) NOT NULL COMMENT 'Name',
email varchar(255) NOT NULL COMMENT 'Email Address',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'John Doe', 'john@gmail.com'),
(2, 'Vanya Hargreeves', 'vanya@gmail.com'),
(3, 'Luther Hargreeves', 'luther@gmail.com'),
(4, 'Diego Hargreeves', 'diego@gmail.com'),
(5, 'Klaus Hargreeves', 'klaus@gmail.com'),
(6, 'Ben Hargreeves', 'ben@gmail.com'),
(7, 'The Handler', 'handler@gmail.com');
Add database name, username and password inside the application/config/database.php.
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'test',
'password' => '4Mu99BhzK8dr4vF1',
'database' => 'demo',
'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,
];
CodeIgniter\Database\Exceptions\DatabaseException #8
Unable to connect database : Codeigniter
To fix Codeigniter – cannot connect to MySQL database error, change the hostname based on your local development server e.g MAMPP or XAMPP.
# MAMPP
public $default = [
...
'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
...
]
# XAMPP
public $default = [
...
'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
...
]
Create Model for User
Create a model and manifest a function that fetches all the user records from the database that we will show later using AJAX in the Codeigniter view.
Create app/Models/UserModel.php file and place the following code.
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $allowedFields = ['name', 'email'];
public function getUsers($id = false) {
if($id === false) {
return $this->findAll();
} else {
return $this->getWhere(['id' => $id]);
}
}
}
?>
Create User Controller
Create a controller file name it app/Controllers/CrudController.php and add the following code in it.
It has the compendium of functions and these functions concurrently render the user records from the database and show the main template in the view.
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\UserModel;
class CrudController extends BaseController {
public function index(){
$data['name'] = 'John Doe';
$data['content'] = 'crud/index_crud';
return view('templates/main', $data);
}
public function user_table(){
$model = new UserModel();
$data['users'] = $model->getUsers();
echo view('crud/user_table', $data);
}
}
?>
Define Route
Open app/Config/Routes.php file and add the following route inside of it.
<?php
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*/
$routes->get('/', 'CrudController::index');
$routes->match(['get', 'post'], 'CrudController/user_table', 'CrudController::user_table');
Fetch Records from Database with AJAX
We have to create a view by connecting multiple pieces of code it will help us to display user records using AJAX in Codeigniter.
Create app/Views/templates/main.php file and place the following code inside of it.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<title>Codeigniter AJAX Tutorial - Fetch Data from Database Example</title>
</head>
<body>
<?php echo view($content); ?>
</body>
</html>
Create two view templates concurrently, first manifest app/Views/crud/index_crud.php file and place the following code inside of it.
<div id="userTable"> </div>
<script>
reloadTable()
function reloadTable() {
$.ajax({
url: "<?php echo site_url(); ?>/CrudController/user_table",
beforeSend: function (f) {
$('#userTable').html('Load Table ...');
},
success: function (data) {
$('#userTable').html(data);
}
})
}
</script>
Ideally, create app/Views/crud/user_table.php file and insert the given below code in it.
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $data) { ?>
<tr>
<td><?php echo $data['id']; ?></td>
<td><?php echo $data['name']; ?></td>
<td><?php echo $data['email']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Start the Application
Run the following command to start the application:
php spark serve
Here is the URL that you have to run in the browser:
http://localhost:8080
Here is the output that you will see in your browser: