Codeigniter 3 Create First Ajax CRUD Application

Codeigniter First Ajax CRUD Application. We would love to share with you how to create ajax crud operation in Codeigniter based project. today we will implement ajax crud (create, read update, delete) application in new latest codeigniter without page refresh or reload

We will use boostrap modal and jquery ajax for create codeigniter application crud operation without page reload or refresh. In this example we will show product you list (product management) with pagination and also provide a demo application for your testing. We will attatched a live demo button. click on live demo button and test demo codeigniter crud application in your hand

In this Codeigniter first ajax crud tutorial, You will also learn how to validate form data on client side without sending the form data to server. We will use jQuery plugin for validating a form data on client side.

Contents

  • Download Codeigniter Project
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credential
  • Create Controller
  • Make Model
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter. Download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ and also rename your project folder name to ci-crud.

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/ci-crud';

Create Database With Table

In this step, we need to create database name ajax_crud, so let’s open your phpmyadmin and create the database with the name ajax_crud. After successfully create a database, you can use the below sql query for creating a table in your database.

CREATE TABLE IF NOT EXISTS products (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
title varchar(255) COLLATE utf8_unicode_ci NOT NULL,
product_code varchar(255) COLLATE utf8_unicode_ci NOT NULL,
description text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

Setup Database Credential

Next step, we will connect the ci_crud project with database, so go to application/database.php and setup the database credential here. In this file add your database name, username and password.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'ajax_crud',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Create Controller

Go to application/controllers/ and create a controller name Product.php. In this controller we will create some method/function name list,create,update,get_product_by_id,delete for perfoming a crud operation.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class Product extends CI_Controller {


public function __construct()
	{
		parent::__construct();
	$this->load->helper('url');
		$this->load->model('Product_model');
	}


	public function index()
	{

		$data['products']=$this->Product_model->get_all_Products();
		$this->load->view('product/product_list',$data);
	}

	public function get_product_by_id()
	{
		$id = $this->input->post('id');
		
		$data = $this->Product_model->get_by_id($id);
         
        $arr = array('success' => false, 'data' => '');
        if($data){
        $arr = array('success' => true, 'data' => $data);
        }
		echo json_encode($arr);
	}

	public function store()
	{
		$data = array(
				'title' => $this->input->post('title'),
				'product_code' => $this->input->post('product_code'),
				'description' => $this->input->post('description'),
				'created_at' => date('Y-m-d H:i:s'),
			);
        
        $status = false;

        $id = $this->input->post('product_id');

        if($id){
           $update = $this->Product_model->update($data);
		   $status = true;
        }else{
           $id = $this->Product_model->create($data);
		   $status = true;
        }

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

        echo json_encode(array("status" => $status , 'data' => $data));
	}

	public function delete()
	{
		$this->Product_model->delete();
		echo json_encode(array("status" => TRUE));
	}



}

Make Model

Go to application/models/ and create model name Product_model.php.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Product_model extends CI_Model
{
 
	public function __construct()
	{
		parent::__construct();
		$this->load->database();
	}
 
 
	public function get_all_products()
	{
		$this->db->from('products');
		$query=$this->db->get();
		return $query->result();
	}
	 
 
	public function get_by_id($id)
	{
		$this->db->from('products');
		$this->db->where('id',$id);
		$query = $this->db->get();
 
		return $query->row();
	}
 
       public function create($data){
    	
           $this->db->insert('products', $data);
	   return $this->db->insert_id();
       }

	public function update($data)
	{
		$where = array('id' => $this->input->post('product_id'));
		 $this->db->update('products', $data, $where);
		 return $this->db->affected_rows();

	}
 
	public function delete()
	{
		$id = $this->input->post('product_id');
		$this->db->where('id', $id);
		$this->db->delete('products');
	}
 
 
}

Create Views

Go to application/views/ and create a one view name product_list.php

<!DOCTYPE html>
<html lang="en">
   <head> 
   <title>Codeigniter Ajax Crud Tutorial Without Reload Page- Tuts Make</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
   <link  href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
   <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
   <style type="text/css">
      .error{
      color: red;
      }
   </style>
   </head>
   <body>
   <div class="container">
      <h2>Codeigniter Ajax Crud Tutorial Without Reload Whole Page - <a href="https://www.tutsmake.com" target="_blank">TutsMake</a></h2>
      <br>
      <a href="https://www.tutsmake.com/codeigniter-3-create-first-ajax-crud-application" class="btn btn-secondary">Back to Post</a>
      <a href="javascript:void(0)" class="btn btn-info ml-3" id="create-new-product">Add New</a>
      <br><br>
      <table class="table table-bordered table-striped" id="product_list">
         <thead>
            <tr>
               <th>ID</th>
               <th>Title</th>
               <th>Product Code</th>
               <th>Descriptionn</th>
               <th>Action</th>
            </tr>
         </thead>
         <tbody>
            <?php if($products): ?>   
            <?php foreach($products as $product):?>
            <tr id="product_id_<?php echo $product->id;?>">
               <td><?php echo $product->id;?></td>
               <td><?php echo $product->title;?></td>
               <td><?php echo $product->product_code;?></td>
               <td><?php echo $product->description;?></td>
               <td>
                  <a href="javascript:void(0)" id="edit-product" data-id="<?php echo $product->id;?>" class="btn btn-info">Edit</a>
                  <a href="javascript:void(0)" id="delete-product" data-id="<?php echo $product->id;?>" class="btn btn-danger delete-user">Delete</a>
               </td>
            </tr>
            <?php endforeach;?>
            <?php endif; ?> 
         </tbody>
      </table>
   </div>

   <!-- Model for add edit product -->
   <div class="modal fade" id="ajax-product-modal" aria-hidden="true">
      <div class="modal-dialog">
         <div class="modal-content">
            <div class="modal-header">
               <h4 class="modal-title" id="productCrudModal"></h4>
            </div>
            <div class="modal-body">
               <form id="productForm" name="productForm" class="form-horizontal">
                  <input type="hidden" name="product_id" id="product_id">
                  <div class="form-group">
                     <label for="name" class="col-sm-2 control-label">Title</label>
                     <div class="col-sm-12">
                        <input type="text" class="form-control" id="title" name="title" placeholder="Enter Tilte" value="" maxlength="50" required="">
                     </div>
                  </div>
                  <div class="form-group">
                     <label for="name" class="col-sm-2 control-label">Product Code</label>
                     <div class="col-sm-12">
                        <input type="text" class="form-control" id="product_code" name="product_code" placeholder="Enter Product Code" value="" maxlength="50" required="">
                     </div>
                  </div>
                  <div class="form-group">
                     <label class="col-sm-2 control-label">Description</label>
                     <div class="col-sm-12">
                        <input type="text" class="form-control" id="description" name="description" placeholder="Enter Description" value="" required="">
                     </div>
                  </div>
                  <div class="col-sm-offset-2 col-sm-10">
                     <button type="submit" class="btn btn-primary" id="btn-save" value="create">Save changes
                     </button>
                  </div>
               </form>
            </div>
            <div class="modal-footer">
            </div>
         </div>
      </div>
   </div>
   </body>


</html>

Script logic

Now we will write for script code for get and post form data using the jQuery ajax and validate form data on client side using jQuery validator method.

<script>
   var SITEURL = '<?php echo base_url(); ?>';

   $(document).ready(function () {

      $("#product_list").DataTable();

      /*  When user click add user button */

      $('#create-new-product').click(function () {
         $('#btn-save').val("create-product");
         $('#product_id').val('');
         $('#productForm').trigger("reset");
         $('#productCrudModal').html("Add New Product");
         $('#ajax-product-modal').modal('show');
      });

      /* When click edit user */

      $('body').on('click', '#edit-product', function () {

         var product_id = $(this).data("id");

         $.ajax({
            type: "Post",
            url: SITEURL + "product/get_product_by_id",
            data: {
               id: product_id
            },
            dataType: "json",
            success: function (res) {
               if (res.success == true) {
                  $('#title-error').hide();
                  $('#product_code-error').hide();
                  $('#description-error').hide();
                  $('#productCrudModal').html("Edit Product");
                  $('#btn-save').val("edit-product");
                  $('#ajax-product-modal').modal('show');
                  $('#product_id').val(res.data.id);
                  $('#title').val(res.data.title);
                  $('#product_code').val(res.data.product_code);
                  $('#description').val(res.data.description);
               }
            },
            error: function (data) {
               console.log('Error:', data);
            }
         });
      });

      $('body').on('click', '#delete-product', function () {

         var product_id = $(this).data("id");

         if (confirm("Are You sure want to delete !")) {
            $.ajax({
               type: "Post",
               url: SITEURL + "product/delete",
               data: {
                  product_id: product_id
               },
               dataType: "json",
               success: function (data) {
                  $("#product_id_" + product_id).remove();
               },
               error: function (data) {
                  console.log('Error:', data);
               }
            });
         }
      });

   });

   if ($("#productForm").length > 0) {
      $("#productForm").validate({

         submitHandler: function (form) {

            var actionType = $('#btn-save').val();

            $('#btn-save').html('Sending..');

            $.ajax({
               data: $('#productForm').serialize(),
               url: SITEURL + "product/store",
               type: "POST",
               dataType: 'json',
               success: function (res) {
                 
                 var product = '<tr id="product_id_' + res.data.id + '"><td>' + res.data.id + '</td><td>' + res.data.title + '</td><td>' + res.data.product_code + '</td><td>' + res.data.description + '</td>';
                 product += '<td><a href="javascript:void(0)" id="edit-product" res.data-id="' + res.data.id + '" class="btn btn-info">Edit</a><a href="javascript:void(0)" id="delete-product" res.data-id="' + res.data.id + '" class="btn btn-danger delete-user">Delete</a></td></tr>';
                
                 if (actionType == "create-product") {
                  
                     $('#product_list').prepend(product);
                 } else {
                     $("#product_id_" + res.data.id).replaceWith(product);
                 }

                  $('#productForm').trigger("reset");
                  $('#ajax-product-modal').modal('hide');
                  $('#btn-save').html('Save Changes');
               },
               error: function (data) {
                  console.log('Error:', data);
                  $('#btn-save').html('Save Changes');
               }
            });
         }
      })
   } 
</script>

Start Development server

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

http://localhost/ci-crud/product

Conclusion

In this codeigniter ajax crud tutorial – We have successfully created first ajax crud (create, update, read, delete) project using mysql database.

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

Spread the love

Be First to Comment

Leave a Reply

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