Ajax allows the developers to implement the feature to make requests from client side browser on the server controller without refresh web page, so that they can fetch the data using it and display it in the view file in CodeIgniter 4 applications.
Let’s start create fetch data from controller to view using ajax in applications:
Step 1: Setting Up CodeIgniter 4
Download CodeIgniter 4 from the official website:https://codeigniter.com/user_guide/installation/index.html., and extract download zip file in xampp/htdocs directory.
Edit .env
file, and set the database connection:
database.default.hostname = localhost
database.default.database = your_database_name
database.default.username = your_username
database.default.password = your_password
database.default.DBDriver = MySQLi
Step 2: Create Table in DB
Run the following sql query to create table in Database:
CREATE TABLE data (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
value VARCHAR(100) NOT NULL
);
INSERT INTO data (name, value) VALUES ('Item 1', 'Value 1');
INSERT INTO data (name, value) VALUES ('Item 2', 'Value 2');
INSERT INTO data (name, value) VALUES ('Item 3', 'Value 3');
Step 3: Creating the Model
Go to the app/models
directory and create a model file called DataModel.php
in it:
<?php
namespace App\Models;
use CodeIgniter\Model;
class DataModel extends Model
{
protected $table = 'data';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'value'];
}
Step 4: Creating the Controller
Go to app/Controllers/
directory and create a new file named DataController.php
, and ajax methods in it to pass data from controller to view:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\DataModel;
class DataController extends Controller
{
public function index()
{
return view('data_view');
}
public function fetchData()
{
$dataModel = new DataModel();
$data = $dataModel->findAll();
return $this->response->setJSON($data);
}
}
Step 5: Create Data View
In the app/Views/
directory create a new file data_view.php
to fetch data using ajax from controller method and display it in view:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch Data From Controller to View using Codeigniter 4 - itcodstuff.com</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Data from Controller</h1>
<button id="fetchDataBtn">Fetch Data</button>
<div id="dataContainer"></div>
<script>
$(document).ready(function() {
$('#fetchDataBtn').click(function() {
$.ajax({
url: '<?= base_url('datacontroller/fetchData') ?>',
method: 'GET',
success: function(response) {
let dataContainer = $('#dataContainer');
dataContainer.empty();
response.forEach(function(item) {
dataContainer.append('<p>Name: ' + item.name + ' - Value: ' + item.value + '</p>');
});
},
error: function() {
alert('Error fetching data');
}
});
});
});
</script>
</body>
</html>
Step 7: Define Routes
Edit app/Config/Routes.php
and define the following routes:
$routes->get('/', 'DataController::index');
$routes->get('datacontroller/fetchData', 'DataController::fetchData');
Step 7: Test the Application
Type the url: http://localhost/your_project_name/public/
on browser and test this application