Codeigniter 4 Ajax Get Data From Database Example

Ajax get data from database codeigniter 4; In this tutorial, i will show you how to get data from database in codeigniter 4 using ajax and as well as how to display data.

Sometimes, you are working in codeigniter 4 app. And you have to get the data from the database and display it as well without refreshing the page and reloading it. For this you have to use Jquery and Ajax.

To get data from controller to view using ajax in codeigniter 4. You will learn from scratch how to get data from database in codeigniter 4 using jQuery ajax and as well as how to display data.

CodeIgniter 4 ajax get data form database example; In this tutorial, I will show a list using jquery datatable in codeigniter 4 app. And I would add a view button to that list. So that whenever a visitor clicks on the button. Then there will be an Ajax call and Ajax will get the data from the database and after that bootstrap model will open. on which the data will be displayed.

CodeIgniter 4 Retrieve Data From Database Using AJAX Example

  • Step 1 – Install Codeigniter 4 Application
  • Step 2 – Basic App Configurations
  • Step 3 – Create Database and Table
  • Step 4 – Setup Database Credentials
  • Step 5 – Create Model Class
  • Step 6 – Create Controller Class
  • Step 7 – Create Views
  • Step 8 – Setup Routes
  • Step 9 – Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database and Table

Create a database and table by executing the following SQL query:

CREATE DATABASE demo;

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='demo database' AUTO_INCREMENT=1;

INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'Paul Bettany', '[email protected]'),
(2, 'Vanya', '[email protected]'),
(3, 'Luther', '[email protected]'),
(4, 'John Doe', '[email protected]'),
(5, 'Paul Bettany', '[email protected]'),
(6, 'Vanya', '[email protected]'),
(7, 'Luther', '[email protected]'),
(8, 'Wayne Barrett', '[email protected]'),
(9, 'Vincent Ramos', '[email protected]'),
(10, 'Susan Warren', '[email protected]'),
(11, 'Jason Evans', '[email protected]'),
(12, 'Madison Simpson', '[email protected]'),
(13, 'Marvin Ortiz', '[email protected]'),
(14, 'Felecia Phillips', '[email protected]'),
(15, 'Tommy Hernandez', '[email protected]');

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

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

Step 5 – Create Model Class

Create UserModel.php file. So, visit app/Models/ directory and create UserModel.php.Then add the following code into it:

<?php 
namespace App\Models;
use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email'];
}

Step 6 – Create Controller Class

Create FetchDataController.php file. So, visit app/Controllers directory and create FetchDataController.php.Then add the following code into it:

<?php 
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;

class FetchDataController extends Controller
{
    // show users list
    public function index(){
        $userModel = new UserModel();
        $data['users'] = $userModel->orderBy('id', 'DESC')->findAll();
        return view('list', $data);
    }


    // show single user
    public function singleUser(){
        if($this->request->getVar('id'))
        {
	        $userModel = new UserModel();
	        $data = $userModel->where('id', $id)->first();
	        echo json_encode($data);
        }
    }

}

FetchController crud controller’s methods will work as follows:

  • The index() function renders the users list template into the view.
  • The singleUser() function retrive data from database and send it to view.

Step 7 – Create Views

Create list.php view file, so visit app/views/ directory and create list.php file. Then add the following HTML into list.php file:

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 CRUD App Example - laratutorials.com</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

</head>
<body>

<div class="container mt-4">
    <div class="d-flex justify-content-end">
        <a href="<?php echo site_url('/user-form') ?>" class="btn btn-success mb-2">Add User</a>
    </div>
    <?php
     if(isset($_SESSION['msg'])){
        echo $_SESSION['msg'];
      }
     ?>
  <div class="mt-3">
     <table class="table table-bordered" id="users-list">
       <thead>
          <tr>
             <th>User Id</th>
             <th>Name</th>
             <th>Email</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <?php if($users): ?>
          <?php foreach($users as $user): ?>
          <tr>
             <td><?php echo $user['id']; ?></td>
             <td><?php echo $user['name']; ?></td>
             <td><?php echo $user['email']; ?></td>
             <td>
             <a href="javascript:void(0)" data-id="<?php echo $user['id'];?>" class="btn btn-info view-user">View</a>
              </td>
          </tr>
         <?php endforeach; ?>
         <?php endif; ?>
       </tbody>
     </table>
  </div>
</div>
 

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>


<script type="text/javascript">
  $(document).ready( function () {
      $('#users-list').DataTable();


        $('body').on('click', '.view-user', function () {

         var user_id = $(this).data("id");

         console.log(user_id);

         $.ajax({
            type: "Post",
            url: "<?php echo base_url(); ?>/user-detail",
            data: {
               id: user_id
            },
            dataType: "json",
            success: function (res) {
               if (res.success == true) {
                  $('#userDetailModal').html("User Details");
                  $('#ajax-user-modal').modal('show');
                  $('#user_id').val(res.id);
                  $('#name').val(res.name);
                  $('#email').val(res.email);
               }
            },
            error: function (data) {
               console.log('Error:', data);
            }
         });
      });

  } );

</script>

<div class="modal fade" id="ajax-user-modal" aria-hidden="true">
      <div class="modal-dialog">
         <div class="modal-content">
            <div class="modal-header">
               <h4 class="modal-title" id="userDetailModal"></h4>
            </div>
            <div class="modal-body">
                
                  <div class="form-group">
                     <label for="name" class="col-sm-2 control-label">Name</label>
                     <div class="col-sm-12">
                        <input type="text" class="form-control" id="name" name="name" placeholder="Enter Tilte" value="">
                     </div>
                  </div>
                  <div class="form-group">
                     <label for="name" class="col-sm-2 control-label">Email</label>
                     <div class="col-sm-12">
                        <input type="text" class="form-control" id="email" name="email" value="">
                     </div>
                  </div>
         
            </div>
            <div class="modal-footer">
            </div>
         </div>
      </div>
</div>



</body>
</html>

And the list.php file will display data in Codeigniter 4 app.

Step 8 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

// CRUD RESTful Routes
$routes->setDefaultController('FetchDataController');
$routes->get('list', 'FetchDataController::index');
$routes->post('user-detail', 'FetchDataController::singleUser');

Note that, the routes will be fetch and display data on view.

Step 9 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

Codeigniter 4 ajax get data from database; In this tutorial, you have larned how to get data from database in codeigniter 4 using ajax and as well as how to display data.

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4
  11. Codeigniter 4 Multiple Image Upload with Preview
  12. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  13. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  14. Codeigniter 4 CRUD with Datatables Example
  15. CodeIgniter 4 Server Side DataTable Example

Leave a Comment