PHP Codeigniter 3 Insert Update Delete using JQuery Ajax

PHP Codeigniter 3 Insert Update Delete using JQuery Ajax

In this Post We Will Explain About is PHP Codeigniter 3 Insert Update Delete using JQuery Ajax With Example and Demo.Welcome on Live24u.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Codeigniter Add, Edit, Delete, jquery ajax, jquery-ui Example

In this post we will show you Best way to implement How to insert, update, delete in codeigniter using ajax jquery, hear for CodeIgniter and jQuery/Ajax – CRUD Select, Insert, Update, and Delete Record with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.




Phase 1: Download Fresh Codeigniter 3

In First step I will here offical side download fresh latest version of PHP Codeigniter 3, Therefor if you haven’t any Codeigniter latest version download yet then here click to download from simple step by step here : Download Codeigniter 3.

After First of all Download successfully and then zip file extract clean new project PHP based Codeigniter 3 web application.

Phase 2: Create Database and Configuration

product table:

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

application/config/database.php

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


$active_group = 'default';
$query_builder = TRUE;


$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'YOUR_HOST_NAME',
	'username' => 'YOUR_USER_NAME',
	'password' => 'YOUR_PASSWORD',
	'database' => 'DATABASE_NAME',
	'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
);

Phase 3: Add Route – CodeIgniter CRUD using Ajax,Bootstrap,Models and MySQL

application/config/routes.php

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


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['products'] = "products/index";
$route['itemsCreate']['post'] = "products/stock";
$route['itemsEdit/(:any)'] = "products/edit/$1";
$route['itemsUpdate/(:any)']['put'] = "products/update/$1";
$route['itemsDelete/(:any)']['delete'] = "products/delete/$1";

Phase 4: Create Controller

After that, now first in this steps we have to make one new Codeigniter controller api function display listing, create data, edit data, update data as well as delete data. Therefor make simple Products.php file in this path Codeigniter Like as a application/controllers/Products.php and Add the bellow script in this file:

Also Read :   AngularJS CRUD Insert Update Delete Using PHP MySQLi

application/controllers/Products.php

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

class Products extends CI_Controller {

   public function index()
   {
       $this->load->database();
       if(!empty($this->input->get("search"))){
          $this->db->like('product_name', $this->input->get("search"));
          $this->db->or_like('shortdesc', $this->input->get("search")); 
       }
       $this->db->limit(5, ($this->input->get("page",1) - 1) * 5);
       $query = $this->db->get("products");
       $data['data'] = $query->result();
       $data['total'] = $this->db->count_all("products");
       echo json_encode($data);
   }

   public function stock()
   {
       $this->load->database();
       $insert = $this->input->post();
       $this->db->insert('products', $insert);
       $id = $this->db->insert_id();
       $q = $this->db->get_where('products', array('id' => $id));
       echo json_encode($q->row());
    }
   public function edit($id)
   {
       $this->load->database();
       $q = $this->db->get_where('products', array('id' => $id));
       echo json_encode($q->row());
   }
   public function update($id)
   {
       $this->load->database();
       $insert = $this->input->post();
       $this->db->where('id', $id);
       $this->db->update('products', $insert);
       $q = $this->db->get_where('products', array('id' => $id));
       echo json_encode($insert);
    }
   public function delete($id)
   {
       $this->load->database();
       $this->db->where('id', $id);
       $this->db->delete('products');
       echo json_encode(['success'=>true]);
    }
}

Phase 5: Update View

In this main root step we will new data update HTML view file of simple code welcome_message.php. In this latest file I step by step will write source code of insert data update data delete data and then also more libs like include latest version of the bootstrap, libs of the jquery, as well as more toastr and live twbsPagination. Therefor let’s main files update following this file:

application/views/welcome_message.php

<!DOCTYPE html>
<html>
<head>
	<title>Codeigniter 3 - Ajax CRUD Example</title>
	<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
</head>
<body>
<div class="container">
<div class="row">
  	<div class="col-lg-12 margin-tb">
  	  <div class="pull-left">
  	    <h2>Simple Codeigniter 3 - Ajax CRUD Example</h2>
  	  </div>
  	  <div class="pull-right">
  	    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#create-product"> Create Product</button>
  	  </div>
  	</div>
</div>
<table class="live24u table table-bordered">
	<thead>
	    <tr>
		      <th>product_name</th>
		      <th>Short Desc</th>
		      <th width="200px">Action</th>
	    </tr>
	</thead>
	<tbody>
	</tbody>
</table>


<ul id="pagination" class="pagination-sm"></ul>
<div class="modal fade" id="create-product" tabindex="-1" role="dialog" aria-labelledby="livemodelLbl">
  <div class="modal-dialog" role="document">
    <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>
        <h4 class="modal-product_name" id="livemodelLbl">Create Product</h4>
      </div>
      <div class="modal-body">
            <form data-toggle="validator" action="products/stock" method="POST">
                <div class="live form-group">
                    <label class="live control-label" for="product_name">product_name:</label>
                    <input type="text" name="product_name" class="form-control" data-error="Please enter product_name." required />
                    <div class="live help-block with-errors"></div>
                </div>
                <div class="live form-group">
                    <label class="live control-label" for="product_name">Short Desc:</label>
                    <textarea name="shortdesc" class="live form-control" data-error="Please enter shortdesc." required></textarea>
                    <div class="live help-block with-errors"></div>
                </div>
                <div class="live form-group">
                    <button type="submit" class="live btn crud-submit btn-success">Submit</button>
                </div>
            </form>
      </div>
    </div>
  </div>
</div>

<!-- Edit Product Modal -->
<div class="live modal fade" id="edit-product" tabindex="-1" role="dialog" aria-labelledby="livemodelLbl">
  <div class="live modal-dialog" role="document">
    <div class="modal-content">
      <div class="live modal-header">
        <button type="button" class="live close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-product_name" id="livemodelLbl">Edit Product</h4>
      </div>
      <div class="live modal-body">
            <form data-toggle="validator" action="" method="put">
                <div class="live form-group">
                    <label class="live control-label" for="product_name">product_name:</label>
                    <input type="text" name="product_name" class="form-control" data-error="Please enter product_name." required />
                    <div class="help-block with-errors"></div>
                </div>

                <div class="live form-group">
                    <label class="live control-label" for="product_name">Short Desc:</label>
                    <textarea name="shortdesc" class="form-control" data-error="Please enter shortdesc." required></textarea>
                    <div class="live help-block with-errors"></div>
                </div>
                <div class="live form-group">
                    <button type="submit" class="live btn btn-success crud-submit-edit">Submit</button>
                </div>
            </form>
      </div>
    </div>
  </div>
</div>
</div>
<script type="text/javascript" src="3.1.0/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="jquery.twbsPagination.min.js"></script>
<script src="validator.min.js"></script>
<script type="text/javascript" src="js/toastr.min.js"></script>
<link href="css/toastr.min.css" rel="stylesheet">
<script type="text/javascript">
	var url = "products";
</script>
<script src="/js/product-ajax.js"></script> 
</body>
</html>

Phase 6: Create JS File

In this Final or last step we will Create new directory js on your main server side root directory and make the new file product-ajax.js on that directory. In here step by step product-ajax.js file I write all the source code of (insert update ande delete)CRUD JS that will manage datatables listing, insert data, update data, delete data and main any pagination. Therefor let’s make a new php file and put the following scripts:

Also Read :   Modal Popup using JavaScript jQuery and CSS

js/product-ajax.js

var page = 1;
var active_page = 1;
var all_pages = 0;
var counter_data = 0;
manageData();
function manageData() {
   $.ajax({
      dataType: 'json',
      url: url,
      data: {page:page}
    }).done(function(data){

       all_pages = data.total % 5;
       active_page = page;

       $('#pagination').twbsPagination({
            totalPages: all_pages,
            visiblePages: active_page,
            onPageClick: function (event, pageL) {
                page = pageL;
                if(counter_data != 0){
                   retrivePageInfo();
                }
            }
        });
        manageRow(data.data);
        counter_data = 1;
   });
}

/* Get Page Data*/
function retrivePageInfo() {
    $.ajax({
       dataType: 'json',
       url: url,
       data: {page:page}
	}).done(function(data){
       manageRow(data.data);
    });
}

function manageRow(data) {
    var	tbl_rows = '';
    $.each( data, function( key, value ) {
        tbl_rows = tbl_rows + '<tr>';
        tbl_rows = tbl_rows + '<td>'+value.product_name+'</td>';
        tbl_rows = tbl_rows + '<td>'+value.shortdesc+'</td>';
        tbl_rows = tbl_rows + '<td data-id="'+value.id+'">';
        tbl_rows = tbl_rows + '<button data-toggle="modal" data-target="#edit-product" class="btn btn-primary edit-product">Edit</button> ';
        tbl_rows = tbl_rows + '<button class="btn btn-danger remove-product">Delete</button>';
        tbl_rows = tbl_rows + '</td>';
        tbl_rows = tbl_rows + '</tr>';
    });
    $("tbody").html(tbl_rows);
}

/* Create new Product */
$(".crud-submit").click(function(e){
    e.preventDefault();
    var form_action = $("#create-product").find("form").attr("action");
    var product_name = $("#create-product").find("input[name='product_name']").val();
    var shortdesc = $("#create-product").find("textarea[name='shortdesc']").val();
    $.ajax({
        dataType: 'json',
        type:'POST',
        url: form_action,
        data:{product_name:product_name, shortdesc:shortdesc}
    }).done(function(data){
        retrivePageInfo();
        $(".modal").modal('hide');
        toastr.success('Product Created Successfully.', 'Success Alert', {timeOut: 5000});
    });
});

/* Remove Product */
$("body").on("click",".remove-product",function(){
    var id = $(this).parent("td").data('id');
    var c_obj = $(this).parents("tr");
    $.ajax({
        dataType: 'json',
        type:'delete',
        url: url + '/' + id,
    }).done(function(data){
        c_obj.remove();
        toastr.success('Product Deleted Successfully.', 'Success Alert', {timeOut: 5000});
        retrivePageInfo();
    });
});

/* Edit Product */
$("body").on("click",".edit-product",function(){
    var id = $(this).parent("td").data('id');
    var product_name = $(this).parent("td").prev("td").prev("td").text();
    var shortdesc = $(this).parent("td").prev("td").text();

    $("#edit-product").find("input[name='product_name']").val(product_name);
    $("#edit-product").find("textarea[name='shortdesc']").val(shortdesc);
    $("#edit-product").find("form").attr("action",url + '/update/' + id);
});


/* Updated new Product */
$(".crud-submit-edit").click(function(e){
    e.preventDefault();
    var form_action = $("#edit-product").find("form").attr("action");
    var product_name = $("#edit-product").find("input[name='product_name']").val();
    var shortdesc = $("#edit-product").find("textarea[name='shortdesc']").val();
    $.ajax({
        dataType: 'json',
        type:'POST',
        url: form_action,
        data:{product_name:product_name, shortdesc:shortdesc}
    }).done(function(data){

        retrivePageInfo();
        $(".modal").modal('hide');
        toastr.success('Product Updated Successfully.', 'Success Alert', {timeOut: 5000});
    });
});

Run Project

Last steps you can simple your localhost server open bellow URL on your any mozila or chrome or other any browser:

Also Read :   AngularJS Line Chart using ChartJS with PHP MySQLi

http://localhost:8000/

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example





Example

I hope you have Got What is Insert, Update, Delete and Select Data with AJAX in CodeIgniter And how it works.I would Like to have FeedBack From My Blog(live24u.com) readers.Your Valuable FeedBack,Any Question,or any Comments about This Article(live24u.com) Are Most Always Welcome.