Codeigniter 4 CRUD Operation Using Ajax Tutorial

Codeigniter 4 is the latest version of the popular PHP framework Codeigniter. It is a powerful and lightweight framework that can be used to create robust web applications. In this tutorial, we will learn how to perform CRUD (Create, Read, Update, and Delete) operations using Ajax in Codeigniter 4.

We will be using the Codeigniter 4 framework and the jQuery library for this tutorial. We will also be using the Codeigniter 4 Model-View-Controller (MVC) architecture to structure our application.

Step 1: Setting up the Project

First, we need to set up our project. We will be using the Codeigniter 4 framework for this tutorial. To get started, download the Codeigniter 4 framework from the official website.

Once you have downloaded the framework, extract the zip file and copy the contents into your web server’s root directory.

Step 2: Setting up the Database

Next, we need to set up the database for our application. We will be using MySQL for this tutorial. Create a new database and name it “crud_ajax”.

Once the database is created, open the “crud_ajax” database and create a new table named “users”. The “users” table should have the following fields:

id (int, primary key, auto-increment)
name (varchar)
email (varchar)

Step 3: Configuring the Database

Now that we have created the database, we need to configure it in the Codeigniter 4 application. Open the “app/Config/Database.php” file and enter the database credentials.

Step 4: Creating the Model

Next, we need to create the Model for our application. The Model is responsible for interacting with the database. Create a new file named “User.php” in the “app/Models” directory and add the following code to it:

findAll();
return view(‘users’, $data);
}

public function create()
{
return view(‘create’);
}

public function store()
{
helper([‘form’, ‘url’]);

$model = new User();

$data = [
‘name’ => $this->request->getVar(‘name’),
’email’ => $this->request->getVar(’email’)
];

$model->save($data);

return redirect()->to(base_url(‘users’));
}

public function edit($id = null)
{
$model = new User();

$data[‘user’] = $model->find($id);

return view(‘edit’, $data);
}

public function update()
{
helper([‘form’, ‘url’]);

$model = new User();

$id = $this->request->getVar(‘id’);

$data = [
‘name’ => $this->request->getVar(‘name’),
’email’ => $this->request->getVar(’email’)
];

$model->update($id, $data);

return redirect()->to(base_url(‘users’));
}

public function delete($id = null)
{
$model = new User();

$model->delete($id);

return redirect()->to(base_url(‘users’));
}
}

Step 6: Creating the Views

Now that we have created the Controller, we need to create the Views for our application. The Views are responsible for displaying the HTML output to the user. Create a new folder named “Views” in the “app” directory and add the following files to it:

users.php

Users


Name Email Action
“>Delete

” method=”post”>







edit.php

Edit User

Name:
Email:

Step 7: Setting up the Routes

Now that we have created the Views, we need to set up the Routes for our application. The Routes are responsible for mapping the user requests to the appropriate Controller action. Open the “app/Config/Routes.php” file and add the following code to it:

$routes->get(‘users’, ‘UserController::index’);
$routes->get(‘user/create’, ‘UserController::create’);
$routes->post(‘user/store’, ‘UserController::store’);
$routes->get(‘user/edit/(:num)’, ‘UserController::edit/$1’);
$routes->post(‘user/update’, ‘UserController::update’);
$routes->get(‘user/delete/(:num)’, ‘UserController::delete/$1’);

Step 8: Adding the JavaScript

Now that we have set up the Routes, we need to add the JavaScript code for our application. Create a new file named “script.js” in the “public/js” directory and add the following code to it:

$(document).ready(function(){
$(‘.delete-user’).on(‘click’, function(e){
e.preventDefault();
var id = $(this).data(‘id’);
$.ajax({
url: ‘user/delete/’+id,
type: ‘DELETE’,
success: function(result) {
window.location.href=’users’;
}
});
});
});

Step 9: Adding the HTML

Finally, we need to add the HTML code for our application. Open the “views/users.php” file and add the following code to it:

Users

Name Email Action
“>Create

And that’s it! You have successfully created a CRUD application using Ajax in Codeigniter 4.
[ad_1]

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.

CRUD Operations in CodeIgniter 4 using jQuery Ajax

Follow the following steps to implement crud operations apps in codeigniter 4 using ajax:

  • 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 @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 [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.

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00