Breaking

Rabu, 22 Januari 2020

DATATABLES NODEJS

Selamat malam, menjelang pagi sobat,
kali ini  baru saja selesai pembuatan crud search mengunakan datatable, datatable adalah salah satu library yang memudahkan kita untuk melakukan editing database (cread, update, delete, search, pagination dan order) via browser.

Semoga bisa membantu sobat sekalian semua yang mumet cari cari referensi datatables menggunakan node js yang memang didominasi oleh platform PHP, Jadi sobat diharapkan sudah membuat aplikasi dengan platform node js (web server ) untuk bisa menambahkan script-script utama yang saya lampirkan, Saya sediakan link script utuhnya di ulasan terkhir.

# Berikut potongan script utama untuk inisialisasinya yang bisa ditempel di html page kita, taruh di head. Posisi script script dibawah ini berada di sisi client

<link href="/assets/datatables/css/dataTables.bootstrap.css"rel="stylesheet">

# Berikut table id nya:

 

        <tableid="table"class="table table-striped table bordered" cellspacing="0" width="100%">

 

             <thead>

                  <tr>

                        <th>namainput</th> 

                          <th>id_user</th> 

                          <th>pin1</th>

                          <th>pin2</th>

                         <th>driver</th>

                         <th style="width:125px;">Action</th>

                  </tr>

             </thead>

             <tbody>

             </tbody>

         </table>



# Berikut pemanggilan datatable scriptnya

$(document).ready(function() {//datatablestable = $('#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": "/iot/digitalinout1","type": "POST"}, //Set column definition initialisation properties."columnDefs": [

{

"targets": [ -1 ], //last column

"orderable": false, //set not orderable

},

],

});

# Berikut potongan script utama untuk sisi server.
// read semua parameter io, call by ajax

router.get('/iot/digitalinout', isLoggedIn, function(req, res, next) {

  Digitalinout.find(function (err, results) {   if (err)

{

return res.write('Error!');

} 

res.json(results)

});});  //ini testing data table komplit search, sort dllrouter.post('/iot/digitalinout1',

isLoggedIn, function(req, res, next) {

  var r ={}; r = req.body  var range = Number(req.body.start)           var limit = Number(req.body.length)          var aquery = r["search[value]"]          var order = r["order[0][dir]"]   if(+r["order[0][column]"]==0){var sort = {namainput:

order}; }////created_at: "asc"

          if(+r["order[0][column]"]==1){var sort = {id_user:order}; }////created_at: "asc"

          if(+r["order[0][column]"]==2){var sort = {pin1: order}; }////created_at: "asc"

          if(+r["order[0][column]"]==3){var sort = {pin2: order}; }////created_at: "asc"

          if(+r["order[0][column]"]==4){var sort = {driver:order}; }////created_at: "asc"

          var populate = ""

  console.log("test isi search = "+aquery) //search

  console.log("test isi dir = "+r["order[0][dir]"]) //desc dan asc

  console.log("test isi column = "+r["order[0][column]"]) //0, 1,2,3

if (populate == null) {

populate = "user";

}

    if (order == null ) {

            sort = {

        //created_at: "asc"

        namainput: "asc"

    

};

    }

console.log("populate = "+populate)

var querytest= {"namainput": {'$regex':aquery},

"id_user": req.user }               

//  Digitalinout.find(querytest).skip(range).limit(limit).sort(sort).exec(function(error, value){Digitalinout.count().exec(function(err, count){

  Digitalinout.count(querytest).exec(function(err, count){  

  Digitalinout.find(querytest)    .skip(range)    .limit(limit)    .sort(sort)    .exec(function(error, value){

if (limit === 1&& !error) {

if (value.length

=== 0) {

error = {

code: 402,

message: "Not found."};

}

value = value[0];

    }

//var row =[]

row = value

  var budi =[]

  var budia =[]

    for(var i=0; i < value.length; i++){ //var budi =[["a","b","c","d","e",row],["f","g","h","j","j",row]]

        budi.push(value[i].namainput)   budi.push(value[i].id_user)        budi.push(value[i].pin1)     budi.push(value[i].driver)    

/* budi.push(value[i].spi_miso)

     budi.push(value[i].spi_mosi)     budi.push(value[i].spi_clk)     budi.push(value[i].i2c_sda)     budi.push(value[i].i2c_scl)     budi.push(value[i].i2c_sclk)     budi.push(value[i].pullupdown)     budi.push(value[i].enable)     budi.push(value[i].description)     */

var idnya ="'"+value[i]._id+"'"

//   var row = "<a class='btn btn-sm btn-primary' href='javascript:void(0)' title='Edit' onclick='edit_input('5e22a286dd8e60880d03fe01')'>Editor</a>";

var row='<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_input('+idnya+')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>';  

var row1='<a class="btn btn-sm btn-danger"

href="javascript:void(0)" title="Hapus" onclick="delete_input('+idnya+')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';

budi.push(row+row1)     budia.push(budi)  

budi =[]

    } 

var data = {"draw": req.body.draw,

     "recordsFiltered": count, //value.length,          "recordsTotal":count,          "data":budia

      };

      console.log("value.length = "+value.length)

    res.json(data)

})})})

// Update digitalinout by ID via ajax

 router.put('/digitalinout/:id', isLoggedIn, function (req, res, next){    var idurl = req.params; // untuk id di uRL       var dariform = req.body;

// untuk body form

    Digitalinout.findByIdAndUpdate(idurl.id , {         namainput : dariform.namainput,        id_user : req.user,        pin1      : dariform.pin1,        pin2: dariform.pin2,        driver: dariform.driver,        spi_miso: dariform.spi_miso,        spi_mosi: dariform.spi_mosi,         spi_clk: dariform.spi_clk,         i2c_sda: dariform.i2c_sda,                 i2c_scl: dariform.i2c_scl,

i2c_sclk: dariform.i2c_sclk,

        enable: dariform.enable,        pullupdown: dariform.pullupdown,           description: dariform.description         },    function(err, result) {  if (err) throw err;

    // we have the updated user returned to us

    //console.log("update Digitalinout baruo" +

result);

//    inisialinput()

    res.json(result) //hasil dikembalikan ke Ajax "data"

 

});

  }); 

  //punya crud datatable

 router.get('/digitalinoutget/:id', isLoggedIn, function (req, res, next){

  var urlid = req.params;  Digitalinout.findById(urlid.id, function(err, result) {

 //router.delete dari bootstrapt bisa error kan backend jika id kosong.

  

if (err) throw err;

      //req.flash('success', 'kit di hapus!'); //

    // console.log("berhasil remove" + result)   

res.json(result) //hasil pembuangan di dikembalikan ke ajax

  

});});

// Delete sensor by ID

router.delete('/digitalinout/:id', isLoggedIn, function(req, res, next) {

    var urlid = req.params;

  Digitalinout.findByIdAndRemove(urlid.id, function(err, result) { 

//router.delete dari bootstrapt bisa error kan backend jika id kosong.

   if (err) throw err;      //req.flash('success', 'kit di hapus!'); // console.log("berhasil remove" + result)    

res.json(result) //hasil pembuangan di dikembalikan ke ajax

  

});});

Nah demikian saya akhiri ulasan pembuatan crud menggunakan datatable. bagi sobat sekalian yang ingin sript utuh bisa klik link ini sebagai source codenya,


Berikut tampilan tampilan yang sudah di screen shot:

# Add Input (form tipe modal)



# List Input





# Search Input








ref :https://medium.com/@deepika.gunda/series-datatables-with-nodejs-express-and-mongodb-part1-get-a-database-to-work-with-7ce78848023e


https://mbahcoding.com/tutorial/php/codeigniter/codeigniter-ajax-crud-using-bootstrap-modals-and-datatable.html

Tidak ada komentar:

Posting Komentar

close