DataTables Server-side Processing in Codeigniter

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

class Form extends CI_Controller {

function __construct()
{
parent:: __construct();
$this->load->model('form_model');

}

public function serverside()
    {
        $this->load->view('include/header');
        $this->load->view('form/server-side-datatable');
        $this->load->view('include/footer');
    }

public function get_form_data()
    {
        $columns = array(
            0 => 'id',
            1 => 'text',
            2 => 'dropdown',
            3 => 'radio',
            4 => 'status',
            5 => 'cdate',
            6 => 'udate',
        );
        $limit = $this->input->post('length');
        $start = $this->input->post('start');
        $order = $columns[$this->input->post('order')[0]['column']];

        $dir = $this->input->post('order')[0]['dir'];

        $total_formdata = $this->form_model->get_formdata_count();

        $total_filter = $total_formdata;

        if (empty($this->input->post('search')['value'])) {
            $formdatas = $this->form_model->get_formdata( $limit, $start, $order, $dir);
        } else {
            $search = $this->input->post('search')['value'];
            $formdatas = $this->form_model->formdata_search( $limit, $start, $search, $order, $dir);

            $total_filter = $this->form_model->formdata_search_count( $search);
        }

        $data = array();

        if (!empty($formdatas)) {
            foreach ($formdatas as $formdata) {
                $nestedData['text']     = $formdata->text;
                $nestedData['dropdown'] = $formdata->dropdown;
                $nestedData['radio']    = $formdata->radio;
                $nestedData['status']   = $formdata->status ? '<div class="text-center table-actions"><a class="table-actions" href=""><i class="btn-success btn">InActive</i></a></div>':'<div class="text-center table-actions"><a class="table-actions" href=""><i class="btn-info btn">Active</i></a></div>';
               
                $nestedData['cdate']    = $formdata->cdate;
                $nestedData['udate']    = $formdata->udate;
               
                $nestedData['actions']  = '<div class="text-center table-actions"><a class="table-actions" href="' . base_url() . 'form/edit_form/' . $formdata->id . '"><button class="btn btn-primary">Edit</button></a>
                <button onclick="deletedata(' . "'" . $formdata->id . "'" . ')" class="btn btn-danger">Delete</button></div>';
                $data[] = $nestedData;
            }
        }

        $json_data = array(
            "draw"              => intval($this->input->post('draw')),
            "recordsTotal"      => intval($total_formdata),
            "recordsFiltered"   => intval($total_filter),
            "data"              => $data,
        );
        echo json_encode($json_data);
    }
}

Form_model.php   Model

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

class Form_model extends CI_Model {

    public function get_formdata_count()
    {
        $this->db->select('*');
        $query = $this->db->get('tbl_form');
        return $query->num_rows();
    }

    public function get_formdata($limit, $start, $order, $dir)
    {
        $this->db->select('*')
            ->from('tbl_form')
            ->limit($limit, $start)
            ->order_by($order,'DESC', $dir);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result();
        } else {
            return null;
        }
    }

    public function formdata_search($limit, $start, $search, $order, $dir)
    {
        $this->db->select('*')
                 ->like('id', $search)
                 ->or_like('text', $search)
                 ->or_like('dropdown',$search)
                 ->limit($limit, $start)
                 ->order_by($order, $dir);
        $query = $this->db->get('tbl_form');
        if ($query->num_rows() > 0) {
            return $query->result();
        } else {
            return null;
        }
    }

    public function formdata_search_count($search)
    {
        $this->db->like('id', $search)
                 ->or_like('text', $search)
                 ->or_like('dropdown',$search);
        $query = $this->db->get('tbl_form');

        return $query->num_rows();
    }

}

server-side-datatable.php          View 

<div class="container-fluid text-center"> 
  <div class="row content">
    <div class="col-sm-12 text-left">
        <table id="Basicform" class="table table-striped table-bordered nowrap dataTable dt-responsive" style="width:100%">
            <thead>
                <tr>
                    <th>Host</th>
                    <th>Password</th>
                    <th>Port</th>
                    <th>Status</th>
                    <th>Created Date</th>
                    <th>Updated Date</th>
                    <th class="text-center">Actions</th>
                </tr>
            </thead>
            <tbody>
             
            </tbody>
        </table>
    </div>
  </div>
</div>


<script type="text/javascript">
$(document).ready(function () {
        $('#Basicform').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax":{
                "url": "<?php echo base_url('form/get_form_data') ?>",
                "dataType": "json",
                "type": "POST",
                "data":{  '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>' }
            },
            "columns": [
               
                { "data": "text" },
                { "data": "dropdown" },
                { "data": "radio" },
                { "data": "status" },
                { "data": "cdate" },
                { "data": "udate" },
                { "data": "actions" },
            ]
        });   
    });


    function deletedata(id){
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this Data.",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, delete!",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {

                $.ajax({
                    url: "<?php echo base_url('form/delete/')?>" + id,
                    type: "POST",
                    success: function (data) {
                        swal({
                            title: 'Success!',
                            type: 'success',
                            focusConfirm: false,
                            timer: 2000,
                        });
                        window.setTimeout(function () {
                            location.reload();
                        }, 2000);
                    },
                    error: function () {
                        alert('Not Closed');
                    }
                });
            } else {
                swal("Cancelled", "Your Data is safe :)", "error");
            }
        });
    }

</script>

SQL Script

CREATE TABLE IF NOT EXISTS `tbl_form` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `text` varchar(100) NOT NULL,
  `dropdown` varchar(10) NOT NULL,
  `radio` varchar(10) NOT NULL,
  `checkbox` varchar(100) NOT NULL,
  `singleFile` varchar(100) NOT NULL,
  `multiplefile` varchar(255) NOT NULL,
  `status` tinyint(1) NOT NULL,
  `cdate` datetime(6) NOT NULL,
  `udate` datetime(6) NOT NULL,
  PRIMARY KEY (`id`)

)

Comments

Popular posts from this blog

API

Encryption and Decryption By PHP

Seeder