Input Data CRUD Codeigniter dan AJAX menggunakan Bootstrap modals and DataTables
Pada kesempatan kali ini saya ingin membagikan tutorial cara membuat aplikasi CRUD menggunakan ajax di codeigniter. Nah apa itu AJAX dan bagaimana fungsinya pada aplikasi yang akan kita buat? simak pembahasannya berikut.
Apa Itu AJAX dan Bagaimana Cara Kerjanya?
Website tidak hanya soal konten saja. Jika ingin menjadi webmaster, ada sejumlah hal yang harus Anda pahami, seperti apa itu AJAX. AJAX adalah sebuah singkatan dari Asynchronous Javascript and XML dan mengacu pada sekumpulan teknis pengembangan web (web development) yang memungkinkan aplikasi web untuk bekerja secara asynchronous (tidak langsung) – memproses setiap request (permintaan) yang datang ke server di sisi background.
JavaScript merupakan bahasa coding yang kerap digunakan. Salah satu fungsinya adalah untuk mengelola konten dinamis website dan memungkinkan interaksi user yang dinamis. Layaknya HTML, XML atau eXtensible Markup Language adalah varian lain dari bahasa markup. Jika HTML dirancang untuk menampilkan data, maka XML dirancang untuk memuat dan membawa data.
Baik JavaScript maupun XML bekerja secara asynchronous di dalam AJAX. Alhasil, aplikasi web yang menggunakan AJAX dapat mengirimkan dan menerima data dari server tanpa harus mereload keseluruhan halaman.
Screenshot output program :
Langkah 1 : Persiapan Awal
- Download CodeIgniter
Pada tutorial kali ini kita masih menggunakan codeigniter dengan versi 3. - Download Bootstrap
Bootstrap kita gunakan untuk membuat interface aplikasi yang menarik. kita akan memanfaatkan komponen tabel, button dan modal pada bootstrap. - Download Jquery
Jquery sebagai library javascript yang cukup populer hingga saat ini, membantu kita untuk membuat aplikasi yang interaktif dan membantu menangani penggunaan AJAX di aplikasi. - Download Xampp
Xampp merupakan aplikasi multi fungsi, salah satu yang paling utama adalah sebagai web server (apache) dan sudah tersedia basis data MySQL. - DataTables
DataTable diperlukan untuk menyajikan data inputan dalam sebuah tabel yang dinamis.
Membuat Auto Complete Total Belanja [Javascript]
Membuat Fungsi Terbilang Rupiah [Javascript]
Membuat Format Rupiah [Javascript]
Memasang Template Admin Lte Dengan Library Codeigniter [Template Website]
create database db_penjualan
CREATE TABLE 'tb_supplier' (
'id_supplier' int(10),
'nama_perusahaan' varchar(100),
'alamat' varchar(200),
'nama_sales' varchar(100),
'telp' varchar(20),
'email' varchar(100)
);
-- example data supplier
INSERT INTO `tb_supplier` (`id_supplier`, `nama_perusahaan`, `alamat`, `nama_sales`, `telp`, `email`) VALUES
('', 'PT. MINAKU', 'GRESIK', 'BAGUS', '081', 'bagus@minaku.com'),
('', 'PT WONOKOYO JAYA CORPORINDO', 'SIDOARJO', 'MADE', '000', 'WJES@YAHOO.COM'),
('', 'PT CIOMAS ADI SATWA', 'TABANAN', 'ERLINDA', '0', 'erlinda@yahoo.co.id'),
('', 'CV PANGAN BERKAH SENTOSA', 'JOMBANG', 'DWIK', '0', 'dwik@yahoo.co.id'),
('', 'PT INDO LAUTAN MAKMUR', 'SIDOARJO', 'HARUN', '0', 'harun@gmail.co.id'),
('', 'PT PRIMA BERKAT', 'Jawa', 'adi', '0', 'adi@gmail.com'),
('', 'CV ANUGERAH ARTHA ABADI', 'Surabaya', 'noname', '0', 'nonam@yahoo.co.id'),
('', 'PT AMIN JAYA', 'Sidoarjo jawa timur', 'no name ', '0', 'noname@yahoo.co.id'),
('', 'PT BOLESCA FOODINDO', 'Bandung', 'no name ', '0', 'noname@yahoo.co.id'),
('', 'PT CHAROEN POKPHAND', 'Serang', 'No name', '0', 'noname@yahoo.co.id'),
('', 'PT Cahaya Gunung Foods', 'jakarta', 'no name', '0', 'noname@yahoo.co.id'),
('', 'UD NEW CITRA RASA', 'Banyuwangi', 'noname', '0', 'noname@yahoo.com'),
('', 'UD.MITRA ABADI', 'Lamongan jawa timur', 'no name ', '0', 'noname@yahoo.co.id'),
('', 'SUPRADINASTY', 'Denpasar - Bali', 'noname', '0', 'noname@yahoo.com'),
('', 'PT RAMA PUTRA', 'Surabaya', 'izul ', '0', 'izul@yahoo.com');
$autoload['libraries'] = array();
$autoload['helper'] = array();
$autoload['libraries'] = array('database');
$autoload['helper'] = array('url','form');
2. config.php
$config['base_url'] = 'http://localhost/penjualan';
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db_penjualan',
'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
);
$route['default_controller'] = 'supplier';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Supplier extends CI_Controller { function __construct(){ parent::__construct(); $this->load->model('supplier_model','supplier'); } public function index() { $this->load->view('v_supplier'); } public function ajax_list() { $list = $this->supplier->get_datatables(); $data = array(); $no = $_POST['start']; foreach ($list as $supplier) { $no++; $row = array(); $row[] = '<input type="checkbox" class="data-check" value="'.$supplier->id_supplier.'">'; $row[] = $supplier->nama_perusahaan; $row[] = $supplier->alamat; $row[] = $supplier->nama_sales; $row[] = $supplier->telp; $row[] = $supplier->email; //add html for action $row[] = '<a class="btn btn-success btn-rounded btn-sm" href="javascript:void(0)" title="Edit data" onclick="edit_supplier('."'".$supplier->id_supplier."'".')"><i class="glyphicon glyphicon-pencil"></i></a> <a class="btn btn-danger btn-rounded btn-sm" href="javascript:void(0)" title="Hapus" onclick="delete_supplier('."'".$supplier->id_supplier."'".')"><span class="glyphicon glyphicon-trash"></span></a>'; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->supplier->count_all(), "recordsFiltered" => $this->supplier->count_filtered(), "data" => $data, ); //output to json format echo json_encode($output); } public function ajax_add() { // cek form validation $this->_validate(); //masukkan form data ke dalam array $data = array( 'id_supplier' => '', 'nama_perusahaan' => $this->input->post('nama_perusahaan'), 'alamat' => $this->input->post('alamat'), 'nama_sales' => $this->input->post('nama_sales'), 'telp' => $this->input->post('telp'), 'email' => $this->input->post('email'), ); //Kirim ke model untuk diinput ke DB $insert = $this->supplier->save($data); //Simpan berhasil, kirim notifikasi status=true (berhasil) echo json_encode(array("status" => TRUE)); } public function ajax_edit($id) //tampilkan data yang akan di edit pada form { $data = $this->supplier->get_by_id($id); echo json_encode($data); } public function ajax_update() //fungsi ini untuk menyimpan/update ke DB { // cek form validation $this->_validate(); //masukkan form data ke dalam array $data = array( 'nama_perusahaan' => $this->input->post('nama_perusahaan'), 'alamat' => $this->input->post('alamat'), 'nama_sales' => $this->input->post('nama_sales'), 'telp' => $this->input->post('telp'), 'email' => $this->input->post('email'), ); //Kirim ke model untuk diupdate ke DB $this->supplier->update(array('id_supplier' => $this->input->post('id_supplier')), $data); //Simpan berhasil, kirim notifikasi status=true (berhasil) echo json_encode(array("status" => TRUE)); } public function ajax_delete($id) { //kirim id supplier ke model untuk dihapus di DB $this->supplier->delete_by_id($id); //Hapus berhasil, kirim notifikasi status=true (berhasil) echo json_encode(array("status" => TRUE)); } public function ajax_bulk_delete() { //simpan id_supplier yang diseleksi ke var $list_id (array) $list_id = $this->input->post('id'); //keluarkan id_supplier yang tersimpan di array $list_id foreach ($list_id as $id) { //perintah eksekusi hapus per id_supplier $this->supplier->delete_by_id($id); } //Hapus berhasil, kirim notifikasi status=true (berhasil) 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('nama_perusahaan') == '') { $data['inputerror'][] = 'nama_perusahaan'; $data['error_string'][] = 'Field nama tidak boleh kosong'; $data['status'] = FALSE; } if($this->input->post('alamat') == '') { $data['inputerror'][] = 'alamat'; $data['error_string'][] = 'Field alamat tidak boleh kosong'; $data['status'] = FALSE; } if($this->input->post('nama_sales') == '') { $data['inputerror'][] = 'nama_sales'; $data['error_string'][] = 'Field sales tidak boleh kosong'; $data['status'] = FALSE; } if($this->input->post('telp') == '') { $data['inputerror'][] = 'telp'; $data['error_string'][] = 'Field Telp tidak boleh kosong'; $data['status'] = FALSE; } if($this->input->post('email') == '') { $data['inputerror'][] = 'email'; $data['error_string'][] = 'Field email tidak boleh kosong'; $data['status'] = FALSE; } if($data['status'] === FALSE) { echo json_encode($data); exit(); } } }
<?php
class Supplier_model extends CI_Model{
///AJAX
var $table = 'tb_supplier';
var $column_order = array(null,'nama_perusahaan','alamat','nama_sales','telp',null);
//set column field database for datatable orderable
var $column_search = array('nama_perusahaan','alamat','nama_sales','telp');
//set column field database for datatable searchable just firstname , lastname , address are searchable
var $order = array('id_supplier' => 'desc'); // default order
public function __construct()
{
parent::__construct();
}
//fungsi ini dibuat untuk kebutuhan menampilkan Data Supplier pada Datatable
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)]);
}
}
//Memanggil Datatable - result()
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();
}
//Fungsi untuk menghitung jumlah data hasil filter (searching) pada datatable
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
//Fungsi ini untuk menghitung total jumlah data supplier
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
//Mengambil data supplier berdasarkan ID tertentu
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('id_supplier',$id);
$query = $this->db->get();
return $query->row();
}
//Fungsi untuk menyimpan ke tabel DB
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
//Fungsi untuk update tabel
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
//Fungsi untuk Delete tabel
public function delete_by_id($id)
{
$this->db->where('id_supplier', $id);
$this->db->delete($this->table);
}
///END OF AJAX MODEL
}
<!DOCTYPE html>
<html>
<head>
<link href="<?php echo base_url()?>assets/bootstrap3/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo base_url('assets/datatables/css/dataTables.bootstrap.min.css')?>" rel="stylesheet">
</head>
<body>
<div class='container'>
<h2 align="center">APLIKASI CRUD AJAX DI CODEIGNITER</h2>
<br />
<button class="btn btn-success" onclick="add_supplier()"><span class="glyphicon glyphicon-plus"></span> Add Person</button>
<button class="btn btn-default" onclick="reload_table()"><i class="glyphicon glyphicon-refresh"></i> Reload</button>
<button class="btn btn-danger" onclick="bulk_delete()"><i class="glyphicon glyphicon-trash"></i> Bulk Delete</button>
<br /><br />
<table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th><input type="checkbox" id="check-all"></th>
<th>Nama Supplier</th>
<th>Alamat</th>
<th>Nama Sales</th>
<th>Telp</th>
<th>Email</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
<!-- MODAL ADD/EDIT -->
<!-- Modal start -->
<div class="modal fade" id="modalAdd" tabindex="-1" role="dialog" >
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Modal title</h3>
</div>
<div class="modal-body">
<form action="#" id="form" class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2" >Nama Supplier</label>
<div class="col-md-10">
<input type="hidden" name="id_supplier">
<input name="nama_perusahaan" id="nama_perusahaan" class="form-control" type="text" placeholder="Nama Lengkap..." required>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" >Alamat</label>
<div class="col-md-10">
<textarea name="alamat" class="form-control" id="alamat" placeholder="Ketikkan Alamat..." required="required"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Nama Sales</label>
<div class="col-md-10">
<input type="text" name="nama_sales" class="form-control" id="nama_sales" placeholder="Nama Sales..." required="required">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" >No. Telp (WA)</label>
<div class="col-md-10">
<input name="telp" id="telp" class="form-control" type="text" placeholder="Ketikkan No. Telp..." required>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" >Email</label>
<div class="col-md-10">
<input name="email" id="email" class="form-control" type="email" placeholder="Ketikkan email..." required>
<span class="help-block"></span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" onclick="save()" id="btnSave">Simpan</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
</div>
</div>
</div>
</div>
<!-- Modal End -->
<!-- END MODAL ADD/EDIT -->
<script src="<?php echo base_url()?>assets/jquery/jquery-2.1.4.min.js"></script>
<script src="<?php echo base_url()?>assets/bootstrap3/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.min.js')?>"></script>
<script type="text/javascript">
var save_method; //for save method string
var table;
var base_url = '<?php echo base_url();?>';
$(document).ready(function() {
//datatables <table id="table" ...
table = $('#table').DataTable({
"serverSide": true, //Feature control DataTables' server-side processing mode.
"processing": true,
"language": {
"infoFiltered": "",
"processing": "<img alt='loading...' src='<?php echo base_url()?>/assets/animasi/loading.gif' />"
},
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('supplier/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
//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();
});
//check all
$("#check-all").click(function () {
$(".data-check").prop('checked', $(this).prop('checked'));
});
});
function add_supplier()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modalAdd').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Supplier'); // Set Title to Bootstrap modal title
}
function edit_supplier(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('supplier/ajax_edit')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
//Pindahkan GET data, kirim ke form data untuk ditampilkan
$('[name="id_supplier"]').val(data.id_supplier);
$('[name="nama_perusahaan"]').val(data.nama_perusahaan);
$('[name="alamat"]').val(data.alamat);
$('[name="nama_sales"]').val(data.nama_sales);
$('[name="telp"]').val(data.telp);
$('[name="email"]').val(data.email);
$('#modalAdd').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Supplier'); // 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('supplier/ajax_add')?>";
} else {
url = "<?php echo site_url('supplier/ajax_update')?>";
}
// ajax adding data to database
var formData = new FormData($('#form')[0]); //form id="form"
$.ajax({
url : url,
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modalAdd').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('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
function delete_supplier(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('supplier/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
function bulk_delete()
{
var list_id = [];
$(".data-check:checked").each(function() {
list_id.push(this.value);
});
if(list_id.length > 0)
{
if(confirm('Are you sure delete this '+list_id.length+' data?'))
{
$.ajax({
type: "POST",
data: {id:list_id},
url: "<?php echo site_url('supplier/ajax_bulk_delete')?>",
dataType: "JSON",
success: function(data)
{
if(data.status)
{
reload_table();
}
else
{
alert('Failed.');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
else
{
alert('no data selected');
}
}
</script>
mantap terima kasih gan, saya jadi inginterus belajar
BalasHapus