CodeIgniter, jQuery, MySQL

(Codeigniter) Ajax CRUD using Bootstrap modals and DataTables with server-side validation

Codeigniter Ajax CRUD using Bootstrap modals and DataTables Tutorial series :

  1. Ajax CRUD using Bootstrap modals and DataTables
  2. Ajax CRUD using Bootstrap modals and DataTables with server-side validation
  3. Ajax CRUD using Bootstrap modals and DataTables with image upload
  4. Ajax CRUD using Bootstrap modals and DataTables with Bulk Delete

Previously I have written a tutorial CodeIgniter CRUD Bootstrap Ajax modals and DataTables. Because a lot of requests from readers to me to write tutorial with adding validation. Now I write tutorial like previouse but with completed with validation form. This validation is using ajax server side validation method.

ajax crud bootstrap datatable with server side validation

ajax crud bootstrap datatable with server side validation

ajax crud bootstrap datatable with validation (editing data)

ajax crud bootstrap datatable with validation (editing data)

ajax crud bootstrap datatable with validation (adding data)

ajax crud bootstrap datatable with validation (adding data)

 

ajax crud bootstrap datatable with validation (validating data)

ajax crud bootstrap datatable with validation (validating data)

Here several framework and library:

  1. PHP+ MySQL or you may use XAMPP –> Download
  2. Codeigniter 3.0.2 –> 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

 

step 1. create database and table. I have database named crud and persons as table for example:

run this query:

create database crud;
use crud;
CREATE TABLE `persons` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `firstName` varchar(100) DEFAULT NULL,
  `lastName` varchar(100) DEFAULT NULL,
  `gender` enum('male','female') DEFAULT NULL,
  `address` varchar(200) DEFAULT NULL,
  `dob` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- example data persons
INSERT INTO `persons` (`id`, `firstName`, `lastName`, `gender`, `address`, `dob`)
VALUES
    (1, 'Airi', 'Satou', 'female', 'Tokyo', '1964-03-04'),
    (2, 'Garrett', 'Winters', 'male', 'Tokyo', '1988-09-02'),
    (3, 'John', 'Doe', 'male', 'Kansas', '1972-11-02'),
    (4, 'Tatyana', 'Fitzpatrick', 'male', 'London', '1989-01-01'),
    (5, 'Quinn', 'Flynn', 'male', 'Edinburgh', '1977-03-24');

step 2. copy codeigniter you have download to your web server htdocs directory. and create assets folder to codeigniter directory include all javascript and css library like this.

ajax crud bootstrap datatable with validation (assets folder)

assets folder codeigniter

step 3.  config route.php . to configure route for default controller.

config/route.php

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

step 4. create Person_model.php in model directory.

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

class Person_model extends CI_Model {

    var $table = 'persons';
    var $column_order = array('firstname','lastname','gender','address','dob',null); //set column field database for datatable orderable
    var $column_search = array('firstname','lastname','address'); //set column field database for datatable searchable just firstname , lastname , address are searchable
    var $order = array('id' => 'desc'); // default order 

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    private function _get_datatables_query()
    {
        
        $this->db->from($this->table);

        $i = 0;
    
        foreach ($this->column_search as $item) // loop column 
        {
            if($_POST['search']['value']) // if datatable send POST for search
            {
                
                if($i===0) // first loop
                {
                    $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
                    $this->db->like($item, $_POST['search']['value']);
                }
                else
                {
                    $this->db->or_like($item, $_POST['search']['value']);
                }

                if(count($this->column_search) - 1 == $i) //last loop
                    $this->db->group_end(); //close bracket
            }
            $i++;
        }
        
        if(isset($_POST['order'])) // here order processing
        {
            $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
        } 
        else if(isset($this->order))
        {
            $order = $this->order;
            $this->db->order_by(key($order), $order[key($order)]);
        }
    }

    function get_datatables()
    {
        $this->_get_datatables_query();
        if($_POST['length'] != -1)
        $this->db->limit($_POST['length'], $_POST['start']);
        $query = $this->db->get();
        return $query->result();
    }

    function count_filtered()
    {
        $this->_get_datatables_query();
        $query = $this->db->get();
        return $query->num_rows();
    }

    public function count_all()
    {
        $this->db->from($this->table);
        return $this->db->count_all_results();
    }

    public function get_by_id($id)
    {
        $this->db->from($this->table);
        $this->db->where('id',$id);
        $query = $this->db->get();

        return $query->row();
    }

    public function save($data)
    {
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    public function update($where, $data)
    {
        $this->db->update($this->table, $data, $where);
        return $this->db->affected_rows();
    }

    public function delete_by_id($id)
    {
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }


}

step 5. create controller file Person.php

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

class Person extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('person_model','person');
    }

    public function index()
    {
        $this->load->helper('url');
        $this->load->view('person_view');
    }

    public function ajax_list()
    {
        $list = $this->person->get_datatables();
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $person) {
            $no++;
            $row = array();
            $row[] = $person->firstName;
            $row[] = $person->lastName;
            $row[] = $person->gender;
            $row[] = $person->address;
            $row[] = $person->dob;

            //add html for action
            $row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_person('."'".$person->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
                  <a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_person('."'".$person->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
        
            $data[] = $row;
        }

        $output = array(
                        "draw" => $_POST['draw'],
                        "recordsTotal" => $this->person->count_all(),
                        "recordsFiltered" => $this->person->count_filtered(),
                        "data" => $data,
                );
        //output to json format
        echo json_encode($output);
    }

    public function ajax_edit($id)
    {
        $data = $this->person->get_by_id($id);
        $data->dob = ($data->dob == '0000-00-00') ? '' : $data->dob; // if 0000-00-00 set tu empty for datepicker compatibility
        echo json_encode($data);
    }

    public function ajax_add()
    {
        $this->_validate();
        $data = array(
                'firstName' => $this->input->post('firstName'),
                'lastName' => $this->input->post('lastName'),
                'gender' => $this->input->post('gender'),
                'address' => $this->input->post('address'),
                'dob' => $this->input->post('dob'),
            );
        $insert = $this->person->save($data);
        echo json_encode(array("status" => TRUE));
    }

    public function ajax_update()
    {
        $this->_validate();
        $data = array(
                'firstName' => $this->input->post('firstName'),
                'lastName' => $this->input->post('lastName'),
                'gender' => $this->input->post('gender'),
                'address' => $this->input->post('address'),
                'dob' => $this->input->post('dob'),
            );
        $this->person->update(array('id' => $this->input->post('id')), $data);
        echo json_encode(array("status" => TRUE));
    }

    public function ajax_delete($id)
    {
        $this->person->delete_by_id($id);
        echo json_encode(array("status" => TRUE));
    }


    private function _validate()
    {
        $data = array();
        $data['error_string'] = array();
        $data['inputerror'] = array();
        $data['status'] = TRUE;

        if($this->input->post('firstName') == '')
        {
            $data['inputerror'][] = 'firstName';
            $data['error_string'][] = 'First name is required';
            $data['status'] = FALSE;
        }

        if($this->input->post('lastName') == '')
        {
            $data['inputerror'][] = 'lastName';
            $data['error_string'][] = 'Last name is required';
            $data['status'] = FALSE;
        }

        if($this->input->post('dob') == '')
        {
            $data['inputerror'][] = 'dob';
            $data['error_string'][] = 'Date of Birth is required';
            $data['status'] = FALSE;
        }

        if($this->input->post('gender') == '')
        {
            $data['inputerror'][] = 'gender';
            $data['error_string'][] = 'Please select gender';
            $data['status'] = FALSE;
        }

        if($this->input->post('address') == '')
        {
            $data['inputerror'][] = 'address';
            $data['error_string'][] = 'Addess is required';
            $data['status'] = FALSE;
        }

        if($data['status'] === FALSE)
        {
            echo json_encode($data);
            exit();
        }
    }

}

step 6. and the last create for view. person_view.php at views directory

<!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>Ajax CRUD with Bootstrap modals and Datatables</title>
    <link href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/datatables/css/dataTables.bootstrap.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/bootstrap-datepicker/css/bootstrap-datepicker3.min.css')?>" rel="stylesheet">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    </head> 
<body>

    <div class="container">
        <h1 style="font-size:20pt">Ajax CRUD with Bootstrap modals and Datatables with Server side Validation</h1>

        <h3>Person Data</h3>
        <br />
        <button class="btn btn-success" onclick="add_person()"><i class="glyphicon glyphicon-plus"></i> Add Person</button>
        <button class="btn btn-default" onclick="reload_table()"><i class="glyphicon glyphicon-refresh"></i> Reload</button>
        <br />
        <br />
        <table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Gender</th>
                    <th>Address</th>
                    <th>Date of Birth</th>
                    <th style="width:125px;">Action</th>
                </tr>
            </thead>
            <tbody>
            </tbody>

            <tfoot>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Address</th>
                <th>Date of Birth</th>
                <th>Action</th>
            </tr>
            </tfoot>
        </table>
    </div>


<script src="<?php echo base_url('assets/jquery/jquery-2.1.4.min.js')?>"></script>
<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>"></script>
<script src="<?php echo base_url('assets/datatables/js/jquery.dataTables.min.js')?>"></script>
<script src="<?php echo base_url('assets/datatables/js/dataTables.bootstrap.js')?>"></script>
<script src="<?php echo base_url('assets/bootstrap-datepicker/js/bootstrap-datepicker.min.js')?>"></script>


<script type="text/javascript">

var save_method; //for save method string
var table;

$(document).ready(function() {

    //datatables
    table = $('#table').DataTable({ 

        "processing": true, //Feature control the processing indicator.
        "serverSide": true, //Feature control DataTables' server-side processing mode.
        "order": [], //Initial no order.

        // Load data for the table's content from an Ajax source
        "ajax": {
            "url": "<?php echo site_url('person/ajax_list')?>",
            "type": "POST"
        },

        //Set column definition initialisation properties.
        "columnDefs": [
        { 
            "targets": [ -1 ], //last column
            "orderable": false, //set not orderable
        },
        ],

    });

    //datepicker
    $('.datepicker').datepicker({
        autoclose: true,
        format: "yyyy-mm-dd",
        todayHighlight: true,
        orientation: "top auto",
        todayBtn: true,
        todayHighlight: true,  
    });

    //set input/textarea/select event when change value, remove class error and remove text help block 
    $("input").change(function(){
        $(this).parent().parent().removeClass('has-error');
        $(this).next().empty();
    });
    $("textarea").change(function(){
        $(this).parent().parent().removeClass('has-error');
        $(this).next().empty();
    });
    $("select").change(function(){
        $(this).parent().parent().removeClass('has-error');
        $(this).next().empty();
    });

});



function add_person()
{
    save_method = 'add';
    $('#form')[0].reset(); // reset form on modals
    $('.form-group').removeClass('has-error'); // clear error class
    $('.help-block').empty(); // clear error string
    $('#modal_form').modal('show'); // show bootstrap modal
    $('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
}

function edit_person(id)
{
    save_method = 'update';
    $('#form')[0].reset(); // reset form on modals
    $('.form-group').removeClass('has-error'); // clear error class
    $('.help-block').empty(); // clear error string

    //Ajax Load data from ajax
    $.ajax({
        url : "<?php echo site_url('person/ajax_edit/')?>/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {

            $('[name="id"]').val(data.id);
            $('[name="firstName"]').val(data.firstName);
            $('[name="lastName"]').val(data.lastName);
            $('[name="gender"]').val(data.gender);
            $('[name="address"]').val(data.address);
            $('[name="dob"]').datepicker('update',data.dob);
            $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
            $('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title

        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });
}

function reload_table()
{
    table.ajax.reload(null,false); //reload datatable ajax 
}

function save()
{
    $('#btnSave').text('saving...'); //change button text
    $('#btnSave').attr('disabled',true); //set button disable 
    var url;

    if(save_method == 'add') {
        url = "<?php echo site_url('person/ajax_add')?>";
    } else {
        url = "<?php echo site_url('person/ajax_update')?>";
    }

    // ajax adding data to database
    $.ajax({
        url : url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {

            if(data.status) //if success close modal and reload ajax table
            {
                $('#modal_form').modal('hide');
                reload_table();
            }
            else
            {
                for (var i = 0; i < data.inputerror.length; i++) 
                {
                    $('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                    $('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
                }
            }
            $('#btnSave').text('save'); //change button text
            $('#btnSave').attr('disabled',false); //set button enable 


        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
            $('#btnSave').text('save'); //change button text
            $('#btnSave').attr('disabled',false); //set button enable 

        }
    });
}

function delete_person(id)
{
    if(confirm('Are you sure delete this data?'))
    {
        // ajax delete data to database
        $.ajax({
            url : "<?php echo site_url('person/ajax_delete')?>/"+id,
            type: "POST",
            dataType: "JSON",
            success: function(data)
            {
                //if success reload ajax table
                $('#modal_form').modal('hide');
                reload_table();
            },
            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">&times;</span></button>
                <h3 class="modal-title">Person Form</h3>
            </div>
            <div class="modal-body form">
                <form action="#" id="form" class="form-horizontal">
                    <input type="hidden" value="" name="id"/> 
                    <div class="form-body">
                        <div class="form-group">
                            <label class="control-label col-md-3">First Name</label>
                            <div class="col-md-9">
                                <input name="firstName" placeholder="First Name" class="form-control" type="text">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3">Last Name</label>
                            <div class="col-md-9">
                                <input name="lastName" placeholder="Last Name" class="form-control" type="text">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3">Gender</label>
                            <div class="col-md-9">
                                <select name="gender" class="form-control">
                                    <option value="">--Select Gender--</option>
                                    <option value="male">Male</option>
                                    <option value="female">Female</option>
                                </select>
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3">Address</label>
                            <div class="col-md-9">
                                <textarea name="address" placeholder="Address" class="form-control"></textarea>
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3">Date of Birth</label>
                            <div class="col-md-9">
                                <input name="dob" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
                                <span class="help-block"></span>
                            </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>

for example demo you can try this code here:

Preview Demo

you can also download source here:
Download








You Might Also Like

  • edo murdani

    Istimewahh mbahhhhh…
    Izin sedot buat belajar mbahhh… ?

    Ilmu manfaat bgt mbahhh… ???

  • freddy

    Hi mbh, why my modal still keep last value when trying insert database ? where is your to remove it ? thanks

    • Mbah Coding

      u must reset the form when add/edit clicked
      here the jquery code:
      $(‘#form’)[0].reset();

      #form is id attribute form in modal

      • freddy

        Done, thanks for you respond mbah, keep touch !

  • freddy

    Mbah let say i have multiple modal in one page with same form,
    then i’m trying to giving errors in first form then why my second modal also errors before submit it ? i guess this is because same name input type text, how can i prevent that without change all name in every modal, thanks

    Freddy Sidauruk

    • Mbah Coding

      try jquery selector with add form id in front of name. for example my code like this
      $(‘[name=”‘+data.inputerror[i]+'”]’).parent().parent().addClass(‘has-error’); //select parent twice to select div form-group class and add has-error class
      $(‘[name=”‘+data.inputerror[i]+'”]’).next().text(data.error_string[i]); //select span help-block class set text error string

      change it to like this:

      $(‘#form [name=”‘+data.inputerror[i]+'”]’).parent().parent().addClass(‘has-error’); //select parent twice to select div form-group class and add has-error class
      $(‘#form [name=”‘+data.inputerror[i]+'”]’).next().text(data.error_string[i]); //select span help-block class set text error string

      form id must different

      • freddy

        Thanks a lot mbah, mbah i have been develop some cms which has modal upload image and fill in then form, already success make the form but hard to giving validations on image itself, i use dropzone to handle this, if you were me what you will use for handle image upload mbh ? need some suggestion and if you don’t mind again mbah would you make tutorial about it again ?

        Thanks

  • freddy

    Hi mbh i’m came again, sorry for to much asking here !

    so to the point mbh, when edit from which is has checkbox and images how can i show that data in modal, for example checkbox

    $.ajax({
    url: base_url + “product/edit/”+id,
    type: “GET”,
    dataType: “JSON”,
    success: function(data)
    {
    //here is data from database which will show in modal

    var name_tipe= val(data.name_tipe); //consider it for check bok
    if (name_tipe !==”) {
    alert(‘check box has value’);
    $(‘.myCheckbox’).prop(‘checked’, true);
    }
    else

    {
    alert(‘check box has value’);
    $(‘.myCheckbox’).prop(‘checked’, false);
    }

    });

    and in my console i got errors val is not define mbah ? please guid me how to puyt value inside checkbox and images in modal bootsrap mabh ? thanks a lot

  • tanya mbah, aq pake CI 2.1.4 pas blm tak pakein template kodenya bisa pas tak pasang ace admin 1.1.2 mlh g kluar apa-apa, ada solusi gak mbah ?

    • Mbah Coding

      CI 2 blm support kurung di query

      $this->db->group_start();
      Dan
      $this->db->group_end();

      Ya sementara di custom query where aja 🙂

  • ubay

    mbah tanya, aku lagi coba insert data menggunakan jquery ajax , sudah bisa melakukan pengiriman ke server namun cuma 1 colom aja yang terisi, mohon pencerahannya mbah ? kira kira itu salah dimana ya ? di request ajaxnya atau controllernya mbah ?

  • root

    mbah, klo csrf nya diaktifin dan sudah ditambahkan csrf token di ajaxnya, namun wkt di sorting gagal 🙁

  • Muhammad Afuw

    Mbah mo nanya kalo dua tabel joinnya gimana, trus jika ada nama column yang sama diantara dua tabel tersebut, gimana terapinnya pada crud ajax ini.

  • Muhammad Afuw

    joinnya berhasil mbah, tinggal mengakali gimana merename column sama nama diantara dua tabel $this->db->select(‘user_group.nama AS group’); dimana meletakkannya yah??

  • faza sulaiman

    hi mbah saya mau bertanya , saya dah bisa menapilkan datanya tapi saat mencoba menambahkan data terjadi error padahal nama table dan lain lainya udah tak sesauin dengan akan saya buat kira2 ini error kenapa ya mohon pencerahannya

  • faza sulaiman

    halo mbah sangat bermanfaat ilmu saya udah nyoba dan sukses tapi saat saya mau nerapin ke sistem saya kenapa fungsi reload_table() tidak berfungsi?
    saya menggunakan ci 2.2.6

    • freddy

      please use console.log dev tools you teach by yourt self to debug use it, thanks

  • Ali Richard

    Why is my output looks like this? http://imgur.com/r0RIrub

    • freddy

      check config base_url or you didn’t load css and jquery js, by the way did you know Codeignter configuration ? thanks

  • derpapst3000

    Hi guys. Is there a way to store the Time and Date if a new entry was made? I want output date and time when created in the row. Thanx in advance if someone can help me out

  • Rifqi Fardi Pradhana

    kok magic sih mbah saya buka url ajax json nya gak bisa karena $_POST[‘value’][‘search’] nya gak ke defined tp yang download dari mbah muncul di table. emang datatables ngirim post method juga ya sebelum ngambil data json nya?

  • Rifqi Fardi Pradhana

    mbah coding mau tanya dong, kalo pake form ajax gini emang gak bisa pake form_validation() nya codeigniter ya? harus assign manual error handling nya?

  • Lex Luthor

    Hi, how i can change the script ( Model) if my database use join to other tables?

    class Person_model extends CI_Model {
    var $table = ‘persons’;
    var $column = array(‘firstname’,’lastname’,’gender’,’address’,’dob’); //set column field database for order and search
    var $order = array(‘id’ => ‘desc’); // default order

    My query in oracle is:

    $this->db->select(‘A.id_usuario, A.rut_usuario, A.usuario, A.nombres_usuario, A.apellidos_usuario, B.glosa_tipousuario, C.nombre_instcorto, D.nombre_departamento, E.nombre_profesion, F.glosa_estado’);
    $this->db->from(‘gc_usuario A’);
    $this->db->join(‘gc_tipousuario B’, ‘B.id_tipousuario = A.id_tipousuario’);
    $this->db->join(‘gc_institucion C’, ‘C.id_institucion = A.id_institucion’);
    $this->db->join(‘gc_departamento D’, ‘D.id_departamento = A.id_departamento’);
    $this->db->join(‘gc_profesion E’, ‘E.id_profesion = A.id_profesion’);
    $this->db->join(‘gc_estadousuario F’, ‘F.id_estadousuario = A.id_estadousuario’);
    $this->db->order_by(‘A.apellidos_usuario, A.nombres_usuario’, ‘asc’);
    $consulta = $this->db->get();
    return $consulta->result();

    Tnahks a lot. Friend

  • Mohammad Ali

    Hi, thanks for this useful tutorial.
    just I have a question about join between many tables, how to handle join query in this example.

  • mbah mau tanya, kenapa saya submit selalu memanggil alert(‘Error adding / update data’); dan reload_table tidak berfungsi. tapi datanya berhasil masuk ke database. mohon solusinya mbah …

  • Rifqi Fardi

    if you meet any problem with joining tables, this post can help you to make joining table for this tutorial. http://stackoverflow.com/questions/34385680/datatables-joining-tables-search-and-order-stuck-with-codeigniter dont forget to give mark as useful question and useful answer thanks

  • nurmatias

    Mbah … mohon sangat dong mbah dibuatkan tutorial untuk multi search nya….
    Hehhehehe soalnya saya udah coba2 tapi gak bisa…

  • Faridh Wisanggeni

    mbah… saya jalankan done… lalu saya tambahkan ke project saya juga done, kecuali fitur filterSearchnya malah error dan mesti buka halaman datatables.net/TN/1

    apakah karena saya mengubah field ‘id’ menjadi ‘kd_trip’ ??

  • معاذ الغفاري

    Hi mbah, how to integrate your function _validate() with codeigniter form validation?

    thank you

  • Mbah kalau jenis kelamin diambil dari tabel lain bagaimana gan?

    Tq

  • Koco

    untuk posgresql caranya gimana mbah?

  • Baptiste Prophete

    Congratulation for this great tutorial, i’m happy to find it. How can i set validation rules base on regular expression ? exemple No numbers for name.

  • Indriantoadi s

    permisi mbah koding ini kenapa yah errornya ?
    terima kasih

    • Marcelo Quimbita

      I also have this problem… do you have the solution?

    • Wahyu Artadianto

      this cause ur field name inside ur table person different try check in folder model and controller make sure all name same with field in table

    • akshay kesharwani

      this error occurs in two situations:
      1. there is post field name mismatch between view and controller, when you try to save / update your modal field data.
      2. database might contains more / less fields than your home page is loading

    • Nuno Cardoso

      I have the same problem. I´m using Codeogniter 2. When i out in my localhost everything wosrks, bur when i put a letter in search field the error is datatables.net/tn/1. I put in my web server and error change to datatables.net/tn/7…how can i resolve this??????

  • Ricardo Johnny De Karine Morae

    and if I wanted to change the Person_model class variable $ table receive a query join?

  • edo

    mbah tanya.
    sudah saya utak atik tpi belum nemu.

    jumlah field kolom di database sudah sama persis dengan tutorial yang mbah berikan.

    kenapa jadi error gini yahh mbahh..?
    mohon bantuannya 🙂

  • edo murdani

    mau tanya lagi mbahh.
    yang kemarin sudah solved.

    pertanyaannya sekarang adalah
    apakah memang primary key dalam database itu harus bernama id mbah..???
    semisal primary key nya saya ubah jadi id_karyawan,kenapa proses editnya gagal yah mbah,di console juga tidak ada errornya. untuk proses tambah data dan hapus tetap bisa mbah tinggal editnya saja..

    mohon pencerahannya.
    terima kasih

    • Asep Saepuloh

      kalo setau saya tidak harus

      • edo murdani

        sudah solved kok om,
        tengs feedbacknya,,:)

      • edo murdani

        sekarang ada permasalahan lagi om. barangkali bisa bantu om.. 🙂

        di database ane kan ada data type nya yang interger. length nya aku bikin 30 karakter.
        nah waktu aku input atau edit via form modal dari tutor ini. kenapa kok maksimal inputnya ke database itu 10 karakter ya om. padahal aku inputnya lebih dari 20 karakter angka. masuk sih ke database tetapi angkanya itu acak om dan jumlahnya tepat 10 karakter angka,tetapi kalau input angkanya dibawah 11 karakter bisa masuk sesuai inputan dri form modal tadi.sedangkan untuk yang data type varchar baik-baik saja om.

        semoga bisa dimengerti kata-kata saya om,
        maaf nubi.. 🙂

        mohon bantuannya..:)

  • Adem Gürler

    Please ? My database table = “eczane”

    • Adem Gürler

      var $table = ‘eczane’;
      var $column = array(‘EczaneNo’,’TcKimlik’,’EczaciAdi’,’EczaneAdi’,’Telefon’,’CepTelefon’); //set column field database for order and search
      var $order = array(‘EczaneNo’ => ‘desc’); // default order

      Please ?

      • Ahmet Yilmaz

        Mrb, Adem Bey
        Sorun Nedir ? Bu kodlarla bende uğraşmaktayım. Amatörce ama sorunsuz uyarladım kendime…

  • Asep Saepuloh

    Mbah datepicker nya gak jalan ya ?

  • edo murdani

    selamat malam mbah..

    sekarang ada permasalahan lagi mbah. yang kemarin uda solved.

    di database ane kan ada data type nya yang interger. length nya aku bikin 30 karakter.

    nah waktu aku input atau edit via form modal dari tutor mbah ini. kenapa kok maksimal inputnya ke database itu 10 karakter ya om. padahal aku inputnya lebih dari 20 karakter angka. masuk sih ke database tetapi angkanya itu acak mbah dan jumlahnya tepat 10 karakter angka,tetapi kalau input angkanya dibawah 11 karakter bisa masuk sesuai inputan dari form modal tadi.sedangkan untuk yang data type varchar baik-baik saja mbah.

    semoga bisa dimengerti kata-kata saya mbah

    maaf nubi.. 🙂

    mohon bantuannya mbah..:)

    • Saya mencoba bantu, mudah2an betul.
      Untuk data type integer ada batasan maksimal angka yg dimasukan, meskipun dimasukannya pjg, yg akan masuk sesuai batasan integer tsb.
      INT_MIN Minimum value for a variable of type int. -2147483648
      INT_MAX Maximum value for a variable of type int. 2147483647
      CMIIW

      • edo murdani

        maaf late respon mas..

        berarti emank harus di bikin data type varchar ya masss,,??
        jadi kita tinggal nambah i rule validasi wajib inputan angka di controllernya yahh mas ganjar..??

  • Sergo

    hello,

    first of all thank you for this amazing tutorial!

    i have problem about search. it’s showing ajax error when searching unicode characters.
    Also i have tried unmodified code from this site and same error. but when i tried to do the same thing on your demo, it’s working.

    can you help? 🙂

  • Adem Gürler

    ????

    • Ahmet Can Boyraz

      Kardeş bana acil mail atarmısın? boyraz.ahmetcan@gmail.com

      • Adem Gürler

        Kardeşim Teşekkür ederim. İlgileniyorum.

  • Septian Sigit

    Mbah, gimana caranya untuk nama login page sebelum masuk CRUD page ini ya ?

    Regards,
    Sgt

  • Taqim

    mbah, cara nambahin pake YADCF gimana ya? saya sudah coba implement, value kebaca, tapi ga mau sorting

  • Kurniawan Ismail

    baru lihat neh blog. mbah coding emang mak nyusssss

  • Agus Santoso

    Hi Mbah Coding,

    Nice share. I want to ask if I use above examples using CodeIgniter 3.0.6, the code will not work. base_url will return http://[::1]/ instead of http://localhost/ . Because of this, no data will be shown. Do you know how to resolve this?

    I have tried to replace Config.php in systemcoreConfig.php in CodeIgniter 3.0.2 to my installation (CodeIgniter 3.0.6). Now the data has been shown. But another problem comes out, the layout is not properly shown (button edit and delete in each row shown in two rows). Do you know how to resolve this ?

    Thank you very much for your help.

    Best regards,

    Agus

    • Agus Santoso

      Hi Mbah Coding,

      I just read your post in this http://mbahcoding.com/php/codeigniter/codeigniterdynamic-base-url.html and it solve the base_url problem. Thanks 🙂

      But do you know how to resolve the broken layout to be same as your example ? Attached is your sample code in my environment.

      Thank you very much for your help

      Best regards,

      Agus

    • Go to application folder—> config–> you will find this “$config[‘base_url’] = ‘http://localhost/nameofthefolder/’;” and you will be good to go.

      • Agus Santoso

        Hi Gerald,

        Thanks for your help. As stated in my previous post, I have solved first problem as explained in another post by Mbah Coding in this post ( http://mbahcoding.com/php/codeigniter/codeigniterdynamic-base-url.html )

        I added this entries in applicationconfigconfig.php

        $config[‘base_url’] = ((isset($_SERVER[‘HTTPS’]) && $_SERVER[‘HTTPS’] == “on”) ? “https” : “http”);

        $config[‘base_url’] .= “://”.$_SERVER[‘HTTP_HOST’];

        $config[‘base_url’] .= str_replace(basename($_SERVER[‘SCRIPT_NAME’]),””,$_SERVER[‘SCRIPT_NAME’]);

        For second question, sorry I post wrong screenshot. This is the wrong layout problem I faced before. Apparently it’s caused by different version of DataTables css (assetsdatatablescssdataTables.bootstrap.css) . I’m using DataTables 1.10.12. This blog is using DataTables 1.10.7. To solve this problem and still using DataTables 1.10.12, I add the action column width to 150px. (previously the code using 125px).

        Sorry for newbie question MbahCoding. Case closed 🙂

        Best regards,

        Agus

        • Hi Agus,
          Am glad you where able to figure out the issue. cheers.

  • Ahmet Yilmaz

    Some fields are not updated on the row edit form. However, the same fields are updated through phpMyAdmin. I could not find a solution for this problem. Thank you for your help.

  • Njoku Chimauche

    Hello,please how do i integrate a login authentication to this ajax crud,
    Please help meeeeeee!
    Thank you

  • Cuap

    permisi mbah, bagaimana jika validasinya hanya maximal 3 karakter input saja?

  • noname

    mbah klo ada upload image gmn ?

  • Ali Richard

    What i fI’d loike to add a where clause in a query or restrictions?

    • try add query builder on _get_datatables_query() function

  • Junaidi Purwanto

    hello mbah, butuh bantuan banget neh. saya ikutin sesuai dengan contoh yang mbah berikan semua tidak ada masalah. tetapi ketika saya mau menyesuaikan dengan code yang saya buat muncul error seperti ini mbah. hasil jsonnya juga valid. mohon bantuannya mbah.
    terima kasih.

  • Oyedepo Olufemi

    Nice Tutorial. Everything worked perfectly!!!

  • Marcelo Quimbita

    Hello. Im using the tuto of http://mbahcoding.com/tutorial/php/codeigniter/codeigniter-ajax-crud-modal-server-side-validation.html, run very good, but im working in HMVC, y copy the code in modules folder and separate in controlles, model and views, I hve this error:

    A PHP Error was encountered
    Severity: Notice
    Message: Undefined property: Person::$person
    Filename: controllers/Person.php
    Line Number: 20
    Backtrace:
    File: C:xampphtdocsci_cronosapplicationmodulesPersoncontrollersPerson.php
    Line: 20
    Function: _error_handler
    File: C:xampphtdocsci_cronosindex.php
    Line: 292
    Function: require_once
    Fatal error: Call to a member function get_datatables() on null in C:xampphtdocsci_cronosapplicationmodulesPersoncontrollersPerson.php on line 20

    A PHP Error was encountered
    Severity: Error
    Message: Call to a member function get_datatables() on null
    Filename: controllers/Person.php
    Line Number: 20
    Backtrace:

    Helpme please

  • Reza Mahdi

    maff mbah, ada contoh jika diganti dengan CKEDITOR?
    sudah saya utak atik namun pas save data tidak tersimpan/terupdate

    • Reza Mahdi

      Udah bisa mbh, saya akalin pakai onchange

      function () {
      var editor = CKEDITOR.replace( ‘editor’, {} );
      editor.on( ‘change’, function ( ev ) {
      document.getElementById( ‘isi’ ).innerHTML = editor.getData();
      } );
      })();

  • Reza Mahdi

    Mbah, popup datepickernya kok mucul sedikit ya?

    • coba ganti versi jquery nya versi 2 aja. kyknya kurang kompatible sama yg baru

      • Reza Mahdi

        Siip mbah, udh bisa, jquerynya saya ganti

  • Ihsan Dn

    permisi mbah mau nanya project ini kan pada bagian model hanya di definisikan untuk penggunaan 1 database saja. bagaimana cara agar bisa 2 database atau lebih? mohon jawabannya kirim ke email saya ihsandn@gmail.com
    terima kasih mbah

  • gop4sch4s

    kalau edit select ambil database bagaimana pak

  • Ahmad Ramdhani
  • Juan Alonso Duran

    Integration AdminALT not work…? erro js jquerry not work in adminlte template please solution

  • Paskalis Gunawan Wibisono

    mbah coding kalo buat pencarian pakai datepicker keyup di atas table bagaimanaya mbah….
    diatas searh emang sudah ada… tapi saya buat itu… tolong mbah bantuannya

  • sandhi

    di view ada baris coding

    “serverSide”: true, //Feature control DataTables’ server-side processing mode.

    dari mana dan apa kegunaannya?
    saya menemui kesulitan ketika saya mengubah database dan table, sesuai dengan kebutuhan aplikasi saya.

    sekarang masih dalam tahap eksplorasi..

    mohon pencerahannya

  • Wahyu Artadianto

    mbah caranya menyisipkan kode otomatis gimana dan diletakkan dimana
    semisal id nya diganti otomatis menjadi “KAR-001” dst trims yg banyak mbah

  • Firman Firdaus

    ada underscore di penamaan function itu buat apa ya mbah . contoh _validate() kenapa ga validate() aja gitu mbah ?

  • irfanmuhluster

    mau tanya koding ini
    if($this->input->post(‘firstName’) == ”)
    {
    $data[‘inputerror’][] = ‘firstName’;
    $data[‘error_string’][] = ‘First name is required’;
    $data[‘status’] = FALSE;
    }

    artinya harus diisi/ required.. bagaimana caranya kalau aku ingin required dan harus angka / most number ?

  • Gus Bala

    Izin sedot mbah. Terima Kasih

  • Code Coffee Desenvolvimento

    Very hard and not understand how to add join into model

    • Wahyu Artadianto

      just use this
      $tSQL = ” your sql query join here “;

      $query = $this->db->query($tSQL);
      return $query->num_rows();

  • Boy

    Permisi mbah mau nanya tentang editnya, Pas diklik button save fieldnya kok gak mau ngupdate ya? isinya tetep. Solusinya gimana?

    • Wahyu Artadianto

      errornya apa mas bro?

      coba cek di folder viewnya
      pastikan id nya kepanggil

      dataType: “JSON”,
      success: function(data)
      {
      $(‘[name=”id”]’).val(data.id);
      …..
      ……
      }

      • Boy

        udah solved bro makasih 😀

  • yodymada

    mbah gimana nambah 1 kolom di dpan buat nomor urutnya, biar lebih rapi mbah, makasih sebelumnya

    • Wahyu Artadianto

      $data = array();
      $no = $_POST[‘start’];
      foreach ($list as $user) {
      $no++;
      $row = array();
      $row[] = $no;
      $row[] = $tenant->Nama;

  • Jeffryan Syahputra

    nanya mbah, kalo mau pake form validation bawaan CI via ajax nya gimana ya mbah, ada contohnya ga..?
    form validation yang model begini :

    //set validation rules
    $this->form_validation->set_rules(‘name’, ‘Name’, ‘trim|required|xss_clean|callback_alpha_space_only’);

  • akshay kesharwani
  • Ekram Saifuldeen

    im happy to to use your codeigniter datatable plugin but when i add java script method
    the save button doesn’t work and when i alert the error message getting internal server Error
    please help me