Codeigniter 4 Get Records from Database using AJAX Tutorial

Database plays a vital role in storing and handling information remotely; we all know the significance of data in the modern era, aren’t we?

In this extensive Codeigniter 4 tutorial, you will discover how to retrieve stored information or the collection of data from the MySQL database with the help of AJAX.

CodeIgniter is an ultimate elixir for developers who need a resilient ecosystem to develop a full-fledged web application. If you belong to a PHP background, this open-source software could be the best choice for your next project.

This tutorial will help you get data from the database using AJAX in the Codeigniter app; this example of Codeigniter ajax fetch data will help you understand how to get along with Codeigniter and MySQL.

How to Get Data using AJAX in Codeigniter

We would like to give you an overview of how development will occur in this Codeigniter 4 AJAX data retrieval tutorial.

  • Step 1: Create Codeigniter Project
  • Step 2: Generate Data Table in DB
  • Step 3: Add App to Database
  • Step 4: Build Model File
  • Step 5: Add App Logic in Controller
  • Step 6: Register Route
  • Step 7: Create View File
  • Step 8: Run App in Browser

Create Codeigniter Project

Currently, Codeigniter comes with two major versions, 4 and 3, even more with installing process. You can install Codeigniter manually or using the below Composer command.

composer create-project codeigniter4/appstarter

After the installation process is done unzip the package and change the name of the project.

Generate Data Table in DB

To get records from the database, one must have some records in the database; the following query will create the table structure and add user records to the database table.

--
-- 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');

Add App to Database

Getting the records from the database requires connecting the db to Codeigniter app, insert database details in the app/Config/Database.php and execute blazingly fast queries.

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,
    ];

Build Model File

You need to create a model class to define the domain-specific data and business logic and outline the state of the data properties.

Create a model and update the code in app/Models/User.php.

<?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]);
      }
    }

}

Add Business Logic in Controller

The UserController class executes the various process in the backend through functions and models, likewise help to fetch the records from DB. Create the UserController file in the controllers’ folder and insert the business logic into the Controller file.

Update app/Controllers/UserController.php file.

<?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);
    }

}

Register Route

The route manages controller logic; place the provided code in the app/Config/Routes.php to register a new route.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->get('/', 'UserController::index');
$routes->get('/get-records', 'UserController::getRecords');

Create View File

View handles the browser response and shows you the output processed by controller and route, create index.php and output.php files in the Views directory.

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>

After we get the data we use the Bootstrap card to give the commendable look to the data, update code in app/Views/output.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

To run app in the browser, use the PHP artisan command and open the provided url in the browser.

php spark serve
http://localhost:8080

AJAX  Get Data in Codeigniter

Summary

We hope you have assimilated every instruction regarding the usage of AJAX in Codeigniter. We have successfully created the simple module using AJAX; we saw how to retrieve the collection or list of data from the database in the Codeigniter app.

We arbitrarily used AJAX to gratify the performance of Codeigniter. In return, the data retrieval process became dynamic, faster and profound and left us with an immaculate and righteous user experience.