CodeIgniter 4 Ajax Crud with datatables and Bootstrap Modals

Codeigniter

Nicesnippets

1202

09-08-2020


CodeIgniter 4 Ajax Crud with datatables and Bootstrap Modals

Hi Guys,

In this tutorial,I will learn you how to use ajax crud with datatables and bootstrap modals in codeigniter 4.you can easy and simply use ajax crud with datatables and bootstrap modals in codeigniter 4.

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.

In this tutorial, we will create a book crud Ajax web application in CodeIgniter 4, as well as use Bootstrap 4 Models and dataTable js.

Step 1: Download Fresh Codeigniter 4


In First step we will download fresh version of Codeigniter 4, so if you haven't download yet then download from here : Download Codeigniter 4.

Step 2: Basic Configurations

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

In this step, we need to connect our project to the database. we need 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.

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

So go to app/Models/ and create here one model. And you need to create one model name Book_model.

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

}

}

Step 6: Create Controller

Now Go to app/Controllers and create a controller name Book.php. In this controller, we will create some method/function.

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

}

}

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</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>

Step 8: Start Development server

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

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

It will help you....