Codeigniter 4 CRUD Operation Using Ajax Example

Codeigniter 4 CRUD Operation Using Ajax Example

CRUD operations in codeigniter 4 using ajax; in this tutorial, you will learn form scratch how to implement CRUD app using aja x in codeigniter 4 app with model and datatables.

CodeIgniter 4 ajax crud web application with bootstrap 4 modals and datatable js. Here you will learn how to create an ajax crud application in CodeIgniter 4 using bootstrap 4 modals and datatable js. And also learn how to insert, update, and delete data using ajax with datatables and bootstrap models.

This tutorial will cover the following topics:

  • Codeigniter 4 ajax crud with modals,
  • Integrate Datatables in codeigniter 4 app
  • Integrate Bootstrap 5 modal in codeigniter 4 app
  • Read data into MySQL DB
  • Insert data using ajax into MySQL DB
  • Upadte data using ajax into MySQL DB
  • Delete data using ajax into MySQL DB

This tutorial will create a ajax book crud web application in CodeIgniter 4 example, as well as use Bootstrap 4 Models and dataTable js.

CodeIgniter 4 ajax crud with datatables and bootstrap modals

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Create Model and Controller
  • Create Views
  • Start Development server

Step 1: Download Codeigniter Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2: Basic Configurations

Next, you 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.

Set Base URL like this

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

Step 3: Create Database With Table

In this step, you 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 @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@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 [email protected]_CHARACTER_SET_CLIENT */;
/*!40101 SET [email protected]_CHARACTER_SET_RESULTS */;
/*!40101 SET [email protected]_COLLATION_CONNECTION */;

Step 4: Setup Database Credentials

In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like below.

	public $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 and Controller

So go to app/Models/ and create here one model. And you need to create one model name Book_model.php and update the following code into your Book_model.php file:

<?php

namespace App\Models;

use CodeIgniter\Model;
class Book_model extends Model {

    var $table = 'books';
    
    public function __construct() {
        parent::__construct();
        //$this->load->database();
        $db = \Config\Database::connect();
        $builder = $db->table('books');
    }

    public function get_all_books() {
//       $query = $this->db->table('books');
       $query = $this->db->query('select * from books');
//      print_r($query->getResult());
       // $query = $this->db->get();
        return $query->getResult();
    }

    public function get_by_id($id) {
      $sql = 'select * from books where book_id ='.$id ;
      $query =  $this->db->query($sql);
      
      return $query->getRow();
    }

    public function book_add($data) {
        
        $query = $this->db->table($this->table)->insert($data);
       
        return $this->db->insertID();
    }

    public function book_update($where, $data) {
        $this->db->table($this->table)->update($data, $where);
//        print_r($this->db->getLastQuery());
        return $this->db->affectedRows();
    }

    public function delete_by_id($id) {
        $this->db->table($this->table)->delete(array('book_id' => $id)); 
    }

}

Create Controller

Now Go to app/Controllers and create a controller name Book.php. In this controller add the follwoing code:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Book_model;
class Book extends Controller {


    public function index() {
        
        helper(['form', 'url']);
        $this->Book_model = new Book_model();
        $data['books'] = $this->Book_model->get_all_books();
        return view('book_view', $data);
    }

    public function book_add() {

        helper(['form', 'url']);
        $this->Book_model = new Book_model();

        $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->Book_model->book_add($data);
        echo json_encode(array("status" => TRUE));
    }

    public function ajax_edit($id) {

        $this->Book_model = new Book_model();

        $data = $this->Book_model->get_by_id($id);

        echo json_encode($data);
    }

    public function book_update() {

        helper(['form', 'url']);
        $this->Book_model = new Book_model();

        $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->Book_model->book_update(array('book_id' => $this->request->getPost('book_id')), $data);
        echo json_encode(array("status" => TRUE));
    }

    public function book_delete($id) {

        helper(['form', 'url']);
        $this->Book_model = new Book_model();
        $this->Book_model->delete_by_id($id);
        echo json_encode(array("status" => TRUE));
    }

}

  • Index() – This is used to display users’ list.
  • book_add() – This method is used to insert data into database.
  • book_update() – This is used to update it into the MySQL database.
  • ajax_edit() – This method is used to fetch single record.
  • book_delete() – This method is used to delete data from MySQL database.

Step 6: Create Views

Now you 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</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
</center>
<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">
$(document).ready( function () {
$('#table_id').DataTable();
} );
var save_method; //for save method string
var table;
function add_book()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
//$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
}
function edit_book(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
<?php header('Content-type: application/json'); ?>
//Ajax Load data from ajax
$.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');
}
});
}
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 adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
function delete_book(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data from database
$.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>

In the above file, you have created bootstrap 4 models, which are used to display edit and create book form.

Step 7: Start Development server

For start development server, Go to the browser and hit below the URL.

http://localhost/demo/public/index.php/book

Conclusion

Codeigniter 4 ajax crud operation with bootstrap 4 modals and datatables js example tutorial, you have successfully created a crud application with bootstrap 4 models and datatables js in CodeIgniter 4 application.

Recommended Codeigniter Posts

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Vue JS, Angular JS, React Js, WordPress, and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *