Our social:

Rabu, 07 Februari 2018

(Codeigniter) Ajax CRUD using Bootstrap modals and DataTables

Screenshot :

Ajax CRUD Datatable
Ajax CRUD DataTables
Bootstrap Modals (Adding data)
Bootstrap Modals (Adding data)
ajax crud bootstrap modals datatable edit
Bootstrap Modals (Editing data)

Required and Included on this source :

  1. PHP+ MySQL or you may use XAMPP –> Download
  2. Codeigniter 3.0 –> Download
  3. jQuery 2.1.4 –> Download
  4. Twitter Bootstrap 3.3.5 –> Download
  5. Bootstrap-datepicker 1.4.0 –> Download
  6. DataTables 1.10.7 –> Download

Database and Query :


01create database crud;
02use crud;
03CREATE TABLE `persons` (
04  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
05  `firstName` varchar(100) DEFAULT NULL,
06  `lastName` varchar(100) DEFAULT NULL,
07  `gender` enum('male','female') DEFAULT NULL,
08  `address` varchar(200) DEFAULT NULL,
09  `dob` date DEFAULT NULL,
10  PRIMARY KEY (`id`)
11) ENGINE=InnoDB DEFAULT CHARSET=utf8;
12  
13-- example data persons
14INSERT INTO `persons` (`id`, `firstName`, `lastName`, `gender`, `address`, `dob`)
15VALUES
16    (1, 'Airi', 'Satou', 'female', 'Tokyo', '1964-03-04'),
17    (2, 'Garrett', 'Winters', 'male', 'Tokyo', '1988-09-02'),
18    (3, 'John', 'Doe', 'male', 'Kansas', '1972-11-02'),
19    (4, 'Tatyana', 'Fitzpatrick', 'male', 'London', '1989-01-01'),
20    (5, 'Quinn', 'Flynn', 'male', 'Edinburgh', '1977-03-24');

Configuring Codeigniter :

assets folder structure :
ajax crud bootstrap datatable assets
Assets Folder Codeigniter
Routing

path : config/route.php


1$route['default_controller'] = 'person';
2$route['404_override'] = '';
3$route['translate_uri_dashes'] = FALSE;

Base URL Cofig (required if using Codeigniter 3.0.3 or later)

path : config/config.php

see for dynamic base_url : Dynamic base_url() and site_url() Codeigniter 3.0.3 +
in this source leave empty because using codeigniter 3.0

Source Code

model : Person_model.php
path : application/models/Person_model.php


01'desc'); // default order
02  
03    public function __construct()
04    {
05        parent::__construct();
06        $this->load->database();
07    }
08  
09    private function _get_datatables_query()
10    {
11          
12        $this->db->from($this->table);
13  
14        $i = 0;
15      
16        foreach ($this->column_search as $item) // loop column
17        {
18            if($_POST['search']['value']) // if datatable send POST for search
19            {
20                  
21                if($i===0) // first loop
22                {
23                    $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
24                    $this->db->like($item, $_POST['search']['value']);
25                }
26                else
27                {
28                    $this->db->or_like($item, $_POST['search']['value']);
29                }
30  
31                if(count($this->column_search) - 1 == $i) //last loop
32                    $this->db->group_end(); //close bracket
33            }
34            $i++;
35        }
36          
37        if(isset($_POST['order'])) // here order processing
38        {
39            $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
40        }
41        else if(isset($this->order))
42        {
43            $order = $this->order;
44            $this->db->order_by(key($order), $order[key($order)]);
45        }
46    }
47  
48    function get_datatables()
49    {
50        $this->_get_datatables_query();
51        if($_POST['length'] != -1)
52        $this->db->limit($_POST['length'], $_POST['start']);
53        $query = $this->db->get();
54        return $query->result();
55    }
56  
57    function count_filtered()
58    {
59        $this->_get_datatables_query();
60        $query = $this->db->get();
61        return $query->num_rows();
62    }
63  
64    public function count_all()
65    {
66        $this->db->from($this->table);
67        return $this->db->count_all_results();
68    }
69  
70    public function get_by_id($id)
71    {
72        $this->db->from($this->table);
73        $this->db->where('id',$id);
74        $query = $this->db->get();
75  
76        return $query->row();
77    }
78  
79    public function save($data)
80    {
81        $this->db->insert($this->table, $data);
82        return $this->db->insert_id();
83    }
84  
85    public function update($where, $data)
86    {
87        $this->db->update($this->table, $data, $where);
88        return $this->db->affected_rows();
89    }
90  
91    public function delete_by_id($id)
92    {
93        $this->db->where('id', $id);
94        $this->db->delete($this->table);
95    }
96  
97  
98}

Controller Person.php
path : applications/controllers/Person.php
01load->model('person_model','person');
02    }
03  
04    public function index()
05    {
06        $this->load->helper('url');
07        $this->load->view('person_view');
08    }
09  
10    public function ajax_list()
11    {
12        $list = $this->person->get_datatables();
13        $data = array();
14        $no = $_POST['start'];
15        foreach ($list as $person) {
16            $no++;
17            $row = array();
18            $row[] = $person->firstName;
19            $row[] = $person->lastName;
20            $row[] = $person->gender;
21            $row[] = $person->address;
22            $row[] = $person->dob;
23  
24            //add html for action
25            $row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" onclick="edit_person('." person-="" title="Edit">id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
26                  <a class="btn btn-sm btn-danger" href="javascript:void(0)" onclick="delete_person('." person-="" title="Hapus">id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
27  
28            $data[] = $row;
29        }
30  
31        $output = array(
32                        "draw" => $_POST['draw'],
33                        "recordsTotal" => $this->person->count_all(),
34                        "recordsFiltered" => $this->person->count_filtered(),
35                        "data" => $data,
36                );
37        //output to json format
38        echo json_encode($output);
39    }
40  
41    public function ajax_edit($id)
42    {
43        $data = $this->person->get_by_id($id);
44        echo json_encode($data);
45    }
46  
47    public function ajax_add()
48    {
49        $data = array(
50                'firstName' => $this->input->post('firstName'),
51                'lastName' => $this->input->post('lastName'),
52                'gender' => $this->input->post('gender'),
53                'address' => $this->input->post('address'),
54                'dob' => $this->input->post('dob'),
55            );
56        $insert = $this->person->save($data);
57        echo json_encode(array("status" => TRUE));
58    }
59  
60    public function ajax_update()
61    {
62        $data = array(
63                'firstName' => $this->input->post('firstName'),
64                'lastName' => $this->input->post('lastName'),
65                'gender' => $this->input->post('gender'),
66                'address' => $this->input->post('address'),
67                'dob' => $this->input->post('dob'),
68            );
69        $this->person->update(array('id' => $this->input->post('id')), $data);
70        echo json_encode(array("status" => TRUE));
71    }
72  
73    public function ajax_delete($id)
74    {
75        $this->person->delete_by_id($id);
76        echo json_encode(array("status" => TRUE));
77    }
78  
79}

view : person_view.php
path : application/views/person_view.php


001<!DOCTYPE html>
002<html>
003    <head>
004    <meta charset="utf-8">
005    <meta http-equiv="X-UA-Compatible" content="IE=edge">
006    <meta name="viewport" content="width=device-width, initial-scale=1">
007    <title>Ajax CRUD with Bootstrap modals and Datatables</title>
008    <link href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css')?>" rel="stylesheet">
009    <link href="<?php echo base_url('assets/datatables/css/dataTables.bootstrap.css')?>" rel="stylesheet">
010    <link href="<?php echo base_url('assets/bootstrap-datepicker/css/bootstrap-datepicker3.min.css')?>" rel="stylesheet">
011    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
012    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
013    <!--[if lt IE 9]>
014      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
015      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
016    <![endif]-->
017    </head>
018<body>
019    <div class="container">
020        <h1 style="font-size:20pt">Ajax CRUD with Bootstrap modals and Datatables</h1>
021  
022        <h3>Person Data</h3>
023         
024 
025        <button class="btn btn-success" onclick="add_person()"><i class="glyphicon glyphicon-plus"></i> Add Person</button>
026        <button class="btn btn-default" onclick="reload_table()"><i class="glyphicon glyphicon-refresh"></i> Reload</button>
027         
028 
029         
030 
031        <table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
032            <thead>
033                <tr>
034                    <th>First Name</th>
035                    <th>Last Name</th>
036                    <th>Gender</th>
037                    <th>Address</th>
038                    <th>Date of Birth</th>
039                    <th style="width:125px;">Action</th>
040                </tr>
041            </thead>
042            <tbody>
043            </tbody>
044  
045            <tfoot>
046            <tr>
047                <th>First Name</th>
048                <th>Last Name</th>
049                <th>Gender</th>
050                <th>Address</th>
051                <th>Date of Birth</th>
052                <th>Action</th>
053            </tr>
054            </tfoot>
055        </table>
056    </div>
057  
058<script src="<?php echo base_url('assets/jquery/jquery-2.1.4.min.js')?>"></script>
059<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>"></script>
060<script src="<?php echo base_url('assets/datatables/js/jquery.dataTables.min.js')?>"></script>
061<script src="<?php echo base_url('assets/datatables/js/dataTables.bootstrap.js')?>"></script>
062<script src="<?php echo base_url('assets/bootstrap-datepicker/js/bootstrap-datepicker.min.js')?>"></script>
063  
064  
065<script type="text/javascript">
066  
067var save_method; //for save method string
068var table;
069  
070$(document).ready(function() {
071  
072    //datatables
073    table = $('#table').DataTable({
074  
075        "processing": true, //Feature control the processing indicator.
076        "serverSide": true, //Feature control DataTables' server-side processing mode.
077        "order": [], //Initial no order.
078  
079        // Load data for the table's content from an Ajax source
080        "ajax": {
081            "url": "<?php echo site_url('person/ajax_list')?>",
082            "type": "POST"
083        },
084  
085        //Set column definition initialisation properties.
086        "columnDefs": [
087        {
088            "targets": [ -1 ], //last column
089            "orderable": false, //set not orderable
090        },
091        ],
092  
093    });
094  
095    //datepicker
096    $('.datepicker').datepicker({
097        autoclose: true,
098        format: "yyyy-mm-dd",
099        todayHighlight: true,
100        orientation: "top auto",
101        todayBtn: true,
102        todayHighlight: true, 
103    });
104  
105});
106  
107  
108  
109function add_person()
110{
111    save_method = 'add';
112    $('#form')[0].reset(); // reset form on modals
113    $('.form-group').removeClass('has-error'); // clear error class
114    $('.help-block').empty(); // clear error string
115    $('#modal_form').modal('show'); // show bootstrap modal
116    $('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
117}
118  
119function edit_person(id)
120{
121    save_method = 'update';
122    $('#form')[0].reset(); // reset form on modals
123    $('.form-group').removeClass('has-error'); // clear error class
124    $('.help-block').empty(); // clear error string
125  
126    //Ajax Load data from ajax
127    $.ajax({
128        url : "<?php echo site_url('person/ajax_edit/')?>/" + id,
129        type: "GET",
130        dataType: "JSON",
131        success: function(data)
132        {
133  
134            $('[name="id"]').val(data.id);
135            $('[name="firstName"]').val(data.firstName);
136            $('[name="lastName"]').val(data.lastName);
137            $('[name="gender"]').val(data.gender);
138            $('[name="address"]').val(data.address);
139            $('[name="dob"]').datepicker('update',data.dob);
140            $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
141            $('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title
142  
143        },
144        error: function (jqXHR, textStatus, errorThrown)
145        {
146            alert('Error get data from ajax');
147        }
148    });
149}
150  
151function reload_table()
152{
153    table.ajax.reload(null,false); //reload datatable ajax
154}
155  
156function save()
157{
158    $('#btnSave').text('saving...'); //change button text
159    $('#btnSave').attr('disabled',true); //set button disable
160    var url;
161  
162    if(save_method == 'add') {
163        url = "<?php echo site_url('person/ajax_add')?>";
164    } else {
165        url = "<?php echo site_url('person/ajax_update')?>";
166    }
167  
168    // ajax adding data to database
169    $.ajax({
170        url : url,
171        type: "POST",
172        data: $('#form').serialize(),
173        dataType: "JSON",
174        success: function(data)
175        {
176  
177            if(data.status) //if success close modal and reload ajax table
178            {
179                $('#modal_form').modal('hide');
180                reload_table();
181            }
182  
183            $('#btnSave').text('save'); //change button text
184            $('#btnSave').attr('disabled',false); //set button enable
185  
186  
187        },
188        error: function (jqXHR, textStatus, errorThrown)
189        {
190            alert('Error adding / update data');
191            $('#btnSave').text('save'); //change button text
192            $('#btnSave').attr('disabled',false); //set button enable
193  
194        }
195    });
196}
197  
198function delete_person(id)
199{
200    if(confirm('Are you sure delete this data?'))
201    {
202        // ajax delete data to database
203        $.ajax({
204            url : "<?php echo site_url('person/ajax_delete')?>/"+id,
205            type: "POST",
206            dataType: "JSON",
207            success: function(data)
208            {
209                //if success reload ajax table
210                $('#modal_form').modal('hide');
211                reload_table();
212            },
213            error: function (jqXHR, textStatus, errorThrown)
214            {
215                alert('Error deleting data');
216            }
217        });
218  
219    }
220}
221  
222</script>
223  
224<!-- Bootstrap modal -->
225<div class="modal fade" id="modal_form" role="dialog">
226    <div class="modal-dialog">
227        <div class="modal-content">
228            <div class="modal-header">
229                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
230                <h3 class="modal-title">Person Form</h3>
231            </div>
232            <div class="modal-body form">
233                <form action="#" id="form" class="form-horizontal">
234                    <input type="hidden" value="" name="id"/>
235                    <div class="form-body">
236                        <div class="form-group">
237                            <label class="control-label col-md-3">First Name</label>
238                            <div class="col-md-9">
239                                <input name="firstName" placeholder="First Name" class="form-control" type="text">
240                                <span class="help-block"></span>
241                            </div>
242                        </div>
243                        <div class="form-group">
244                            <label class="control-label col-md-3">Last Name</label>
245                            <div class="col-md-9">
246                                <input name="lastName" placeholder="Last Name" class="form-control" type="text">
247                                <span class="help-block"></span>
248                            </div>
249                        </div>
250                        <div class="form-group">
251                            <label class="control-label col-md-3">Gender</label>
252                            <div class="col-md-9">
253                                <select name="gender" class="form-control">
254                                    <option value="">--Select Gender--</option>
255                                    <option value="male">Male</option>
256                                    <option value="female">Female</option>
257                                </select>
258                                <span class="help-block"></span>
259                            </div>
260                        </div>
261                        <div class="form-group">
262                            <label class="control-label col-md-3">Address</label>
263                            <div class="col-md-9">
264                                <textarea name="address" placeholder="Address" class="form-control"></textarea>
265                                <span class="help-block"></span>
266                            </div>
267                        </div>
268                        <div class="form-group">
269                            <label class="control-label col-md-3">Date of Birth</label>
270                            <div class="col-md-9">
271                                <input name="dob" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
272                                <span class="help-block"></span>
273                            </div>
274                        </div>
275                    </div>
276                </form>
277            </div>
278            <div class="modal-footer">
279                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
280                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
281            </div>
282        </div><!-- /.modal-content -->
283    </div><!-- /.modal-dialog -->
284</div><!-- /.modal -->
285<!-- End Bootstrap modal -->
286</body>
287</html>
sumber