In this tutorial you will learn Codeigniter 4 fetch Data from controller to View using Ajax tutorial. AJAX allows developers to perform asynchronous operations from the client-side without needing to refresh the whole web page. This capability facilitates to get data from the server and updating the content dynamically within CodeIgniter 4 application views.
In this guide, we will explore how to retrieve data from a controller and present it in a view using AJAX:
Step 1: Set Up CodeIgniter 4
- Download CodeIgniter 4 from the official site: CodeIgniter Installation Guide.
- Extract the downloaded zip file into the
xampp/htdocs
directory. - Open the
.env
file and configure your 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 a Database Table
Execute the following SQL commands to create a table named data
in your 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: Create the Model
Navigate to the app/Models
directory and create a new file called DataModel.php
with the following content:
<?php
namespace App\Models;
use CodeIgniter\Model;
class DataModel extends Model
{
protected $table = 'data';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'value'];
}
Step 4: Create the Controller
In the app/Controllers
directory, create a file named DataController.php
. Add the following code to handle AJAX requests and pass data from the controller to the 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 the View
In the app/Views
directory, create a file named data_view.php
. This file will use AJAX to fetch data from the controller and display it:
<!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 in CodeIgniter 4</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 6: Define Routes
Update app/Config/Routes.php
to include the following routes:
$routes->get('/', 'DataController::index');
$routes->get('datacontroller/fetchData', 'DataController::fetchData');
Step 7: Test the Application
Open your browser and navigate to http://localhost/your_project_name/public/
to test the application.
d