Codeigniter 4 Ajax CRUD Operation Example Tutorial

CodeIgniter 4 ajax crud operation example; In this tutorial, i will show you how to implement crud operations in codeigniter 4 using ajax with bootstrap and mysql.

If you want how to perform CRUD operation without page refresh and reload then in this tutorial you will learn how to perform CRUD operation with database using Ajax and bootstrap in codeigniter 4 app that too without web page refresh and reload.

In this Codeigniter 4 ajax crud with bootstrap model using datatable example tutorial, I will cover the following topics:

  • Installing Codeigniter with the composer package.
  • Creating views to handle Ajax CRUD operations.
  • Integrating Bootstrap 4 in Codeigniter.
  • Integrating jQuery in Codeigniter.
  • Integrating DataTables in Codeigniter.
  • Create(insert) data into MySQL DB.
  • Read(Fetch) data using ajax from MySQL DB.
  • Update(Modify) data using ajax from MySQL DB.
  • Delete data using ajax from the MySQL DB.

CRUD Operations in Codeigniter 4 using Ajax

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Model Class
  • Create Controller Class
  • Create Views
  • Setup Routes
  • 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 Book_model.php file. So, visit app/Models/ directory and create Book_model.php.Then add the following code into it:

<?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 Class

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

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Book_model;
class BookController 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_list', $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));
    }

}

UserCrudController crud controller’s methods will work as follows:

  • The index() function renders the users list template into the view.
  • The book_add() function store data into mysql db.
  • The book_edit() function fetch from database.
  • The book_update() function update data into database.
  • The book_delete() function permanently delete data into database.

Step 7 – Create Views

In this step, visit app/Views/ and create some views files for display add, edit form and usres list.

Create book_list.php view file, so visit app/views/ directory and create book_list.php file. Then add the following HTML into book_list.php 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 operation example- laratutorials.com</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('BookController/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('BookController/book_add')?>";
      }
      else
      {
        url = "<?php echo site_url('BookController/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('BookController/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 – 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('BookController');
$routes->get('book_list', 'BookController::index');

Note that, the routes will be create, read, update and delete 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 crud with bootstrap and mysql example;In this tutorial, you have learned successfully how implement ajax crud operation in Codeigniter 4 apps with bootstrap and mysql database.

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
  16. Codeigniter 4 Ajax Get Data From Database Example

Be First to Comment

Leave a Reply

Your email address will not be published.