CodeIgniter 4 CRUD Operation Using Ajax Tutorial
Apr 23, 2022 . Admin

Hi Guys,
I am going to explain you example of codeigniter 4 ajax crud with datatables and bootstrap modals. This tutorial will give you simple example of codeigniter 4 ajax crud with datatables and bootstrap modals. step by step explain codeigniter 4 ajax crud using datatables. you will learn codeigniter 4 ajax crud with datatables and bootstrap modals.
You can easy and simply use ajax crud with datatables and bootstrap modals in codeigniter 4.
So, let's start the example..
Step 1: Install Codeigniter 4This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:
composer create-project codeigniter4/appstarter ci-newsStep 2: Basic Configurations
In this step we will set 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.
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';Step 3: Create Database With Table
In this step, we need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.
-- phpMyAdmin SQL Dump -- version 4.7.2 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Oct 17, 2017 at 04:21 PM -- Server version: 5.7.19-0ubuntu0.17.04.1 -- PHP Version: 7.0.23-1+ubuntu17.04.1+deb.sury.org+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `demo` -- -- -------------------------------------------------------- -- -- Table structure for table `books` -- CREATE TABLE `books` ( `book_id` int(11) NOT NULL, `book_isbn` int(11) NOT NULL, `book_title` varchar(50) NOT NULL, `book_author` varchar(50) NOT NULL, `book_category` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `books` -- INSERT INTO `books` (`book_id`, `book_isbn`, `book_title`, `book_author`, `book_category`) VALUES (1, 101, 'two state', 'Chetan Bhagat', 'Love Story'), (2, 102, 'Half Girl Friend', 'Chetan Bhagat', 'Love Story'); -- -------------------------------------------------------- -- -- Indexes for table `books` -- ALTER TABLE `books` ADD PRIMARY KEY (`book_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `books` -- ALTER TABLE `books` MODIFY `book_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;Step 4: Setup Database Credentials
We need to connect our project to the database. we require to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We need to set up database credentials in this file like below.
app/Config/Database.phppublic $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'demo', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'production'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ];Step 5: Create Model
In this step go to app/Models/ and create here one model. And you need to create one model name BookModel.
app/Models/BookModel.php<?php namespace App\Models; use CodeIgniter\Model; class BookModel extends Model { var $table = 'books'; /** * Write code on Method * * @return response() */ public function __construct() { parent::__construct(); $db = \Config\Database::connect(); $builder = $db->table('books'); } /** * Write code on Method * * @return response() */ public function get_all_books() { $query = $this->db->query('select * from books'); return $query->getResult(); } /** * Write code on Method * * @return response() */ public function get_by_id($id) { $sql = 'select * from books where book_id ='.$id ; $query = $this->db->query($sql); return $query->getRow(); } /** * Write code on Method * * @return response() */ public function book_add($data) { $query = $this->db->table($this->table)->insert($data); return $this->db->insertID(); } /** * Write code on Method * * @return response() */ public function book_update($where, $data) { $this->db->table($this->table)->update($data, $where); return $this->db->affectedRows(); } /** * Write code on Method * * @return response() */ public function delete_by_id($id) { $this->db->table($this->table)->delete(array('book_id' => $id)); } }Step 6: Create Controller
Here, Go to app/Controllers and create a controller name Book.php. In this controller, we will create some method/function.
app/Controllers/Book.php<?php namespace App\Controllers; use CodeIgniter\Controller; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use App\Models\BookModel; class Book extends Controller { /** * Write code on Method * * @return response() */ public function index() { helper(['form', 'url']); $this->BookModel = new BookModel(); $data['books'] = $this->BookModel->get_all_books(); return view('book_view', $data); } /** * Write code on Method * * @return response() */ public function book_add() { helper(['form', 'url']); $this->BookModel = new BookModel(); $data = array( 'book_isbn' => $this->request->getPost('book_isbn'), 'book_title' => $this->request->getPost('book_title'), 'book_author' => $this->request->getPost('book_author'), 'book_category' => $this->request->getPost('book_category'), ); $insert = $this->BookModel->book_add($data); echo json_encode(array("status" => TRUE)); } /** * Write code on Method * * @return response() */ public function ajax_edit($id) { $this->BookModel = new BookModel(); $data = $this->BookModel->get_by_id($id); echo json_encode($data); } /** * Write code on Method * * @return response() */ public function book_update() { helper(['form', 'url']); $this->BookModel = new BookModel(); $data = array( 'book_isbn' => $this->request->getPost('book_isbn'), 'book_title' => $this->request->getPost('book_title'), 'book_author' => $this->request->getPost('book_author'), 'book_category' => $this->request->getPost('book_category'), ); $this->BookModel->book_update(array('book_id' => $this->request->getPost('book_id')), $data); echo json_encode(array("status" => TRUE)); } /** * Write code on Method * * @return response() */ public function book_delete($id) { helper(['form', 'url']); $this->BookModel = new BookModel(); $this->BookModel->delete_by_id($id); echo json_encode(array("status" => TRUE)); } }Step 7: Create Views
Now we need to create one view files name book_view.php and update the following code into your file:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>codeigniter 4 ajax crud with datatables and bootstrap modals - Mywebtuts.com</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <h3>Book Store</h3> <br /> <button class="btn btn-success" onclick="add_book()"><i class="glyphicon glyphicon-plus"></i> Add Book</button> <br /> <br /> <table id="table_id" class="table table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> <th>Book ID</th> <th>Book ISBN</th> <th>Book Title</th> <th>Book Author</th> <th>Book Category</th> <th style="width:125px;">Action</p></th> </tr> </thead> <tbody> <?php foreach($books as $book){?> <tr> <td><?php echo $book->book_id;?></td> <td><?php echo $book->book_isbn;?></td> <td><?php echo $book->book_title;?></td> <td><?php echo $book->book_author;?></td> <td><?php echo $book->book_category;?></td> <td> <button class="btn btn-warning" onclick="edit_book(<?php echo $book->book_id;?>)">Edit</button> <button class="btn btn-danger" onclick="delete_book(<?php echo $book->book_id;?>)">Delete</button> </td> </tr> <?php }?> </tbody> <tfoot> <tr> <th>Book ID</th> <th>Book ISBN</th> <th>Book Title</th> <th>Book Author</th> <th>Book Category</th> <th>Action</th> </tr> </tfoot> </table> </div> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"> <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js" type="text/javascript"></script> <script type="text/javascript"> /*------------------------------------------ -------------------------------------------- DataTable -------------------------------------------- --------------------------------------------*/ $(document).ready( function () { $('#table_id').DataTable(); }); var save_method; var table; /*------------------------------------------ -------------------------------------------- Add Book -------------------------------------------- --------------------------------------------*/ function add_book() { save_method = 'add'; $('#form')[0].reset(); $('#modal_form').modal('show'); } /*------------------------------------------ -------------------------------------------- Edit Book -------------------------------------------- --------------------------------------------*/ function edit_book(id) { save_method = 'update'; $('#form')[0].reset(); // reset form on modals <?php header('Content-type: application/json'); ?> $.ajax({ url : "<?php echo site_url('public/index.php/book/ajax_edit/')?>/" + id, type: "GET", dataType: "JSON", success: function(data) { console.log(data); $('[name="book_id"]').val(data.book_id); $('[name="book_isbn"]').val(data.book_isbn); $('[name="book_title"]').val(data.book_title); $('[name="book_author"]').val(data.book_author); $('[name="book_category"]').val(data.book_category); $('#modal_form').modal('show'); // show bootstrap modal when complete loaded $('.modal-title').text('Edit Book'); // Set title to Bootstrap modal title }, error: function (jqXHR, textStatus, errorThrown) { console.log(jqXHR); alert('Error get data from ajax'); } }); } /*------------------------------------------ -------------------------------------------- About -------------------------------------------- --------------------------------------------*/ function save() { var url; if(save_method == 'add') { url = "<?php echo site_url('public/index.php/book/book_add')?>"; } else { url = "<?php echo site_url('public/index.php/book/book_update')?>"; } $.ajax({ url : url, type: "POST", data: $('#form').serialize(), dataType: "JSON", success: function(data) { $('#modal_form').modal('hide'); location.reload();// for reload a page }, error: function (jqXHR, textStatus, errorThrown) { alert('Error adding / update data'); } }); } /*------------------------------------------ -------------------------------------------- Delete Book -------------------------------------------- --------------------------------------------*/ function delete_book(id) { if(confirm('Are you sure delete this data?')) { $.ajax({ url : "<?php echo site_url('public/index.php/book/book_delete')?>/"+id, type: "POST", dataType: "JSON", success: function(data) { location.reload(); }, error: function (jqXHR, textStatus, errorThrown) { alert('Error deleting data'); } }); } } </script> <!-- Bootstrap modal --> <div class="modal fade" id="modal_form" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h3 class="modal-title">Book Form</h3> </div> <div class="modal-body form"> <form action="#" id="form" class="form-horizontal"> <input type="hidden" value="" name="book_id"/> <div class="form-body"> <div class="form-group"> <label class="control-label col-md-3">Book ISBN</label> <div class="col-md-9"> <input name="book_isbn" placeholder="Book ISBN" class="form-control" type="text"> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Book Title</label> <div class="col-md-9"> <input name="book_title" placeholder="Book_title" class="form-control" type="text"> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Book Author</label> <div class="col-md-9"> <input name="book_author" placeholder="Book Author" class="form-control" type="text"> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Book Category</label> <div class="col-md-9"> <input name="book_category" placeholder="Book Category" class="form-control" type="text"> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button> <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <!-- End Bootstrap modal --> </body> </html>Step 8: Run Codeigniter App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:
php spark serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8080/
It will help you....