简体   繁体   中英

Datatable reordering save to database

Hi guys i'm struggling with the datatables reordering. I want when user reorder to update table in the database. For this to happen i need:

  1. to configure the datatable to send request to the server file which will process the data;
  2. what format will send the datatable to know exactly what the php file will process.

I have read the documentation but it is not clear to me how to send the request from datatable to the file and how to store it in the database.

http://www.datatables.net/reference/option/#rowreorder

Here is my code

  $(document).ready(function () {
    var table =    $('#dattab').DataTable({rowReorder: true,
        dom: 'Bfrtip',
        buttons: [
        'copyHtml5', 'excelHtml5', 'csvHtml5','pdfHtml5'
    ]
    });       
});

I have try some of the options and events in the documentation but i have not seen a post request.

How can be done to store in the database and what fields do I need in the tables in MYSQL.

i have made it to work ... It was my error to use older php. I will share what was my solution:

First the initialization code:

var table = $('#dattab').DataTable({
     rowReorder: {
         selector: 'tr',
         //   update: true,
         //   dataSrc: '.ord-id'
     },
     dom: 'Bfrtip',
     buttons: [
         'copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5'
     ]
 });

Second i was needed to attach event on which to send the ajax request i have try with the reorder but it not helped me for some reason it was sending one redraw old on the table so i use the draw event and it sends the ajax when the table is redrawn:

$('#dattab').on('draw.dt', function () {
       if ($('#dattab').data('tabs')) {
           var rows = table.rows().data();
           var ord = new Array();
           for (var i = 0, ien = rows.length; i < ien; i++) {
               ord[i] = rows[i].DT_RowId;
           }
           post_order(ord, $('#dattab').data('tabs'));
       }
   });

Third i need a php script to handle the reorder:

if( $_POST['elem'] && $_POST['table']) {
$i = 1;
$error = 0;
foreach ($_POST['elem'] as $row) {
    $q = "UPDATE " . "fit_" . $_POST["table"] . " set
        <code>order</code> = ".$i.  "
        ,updated_at = Now()
        WHERE id = " . GetSQLValueString($row, "int");

    $res = $mysqli->query($q);
    $i++;
    if(!$res)
    {
        $error++;
    }

}
if(!$error)
{
    echo 'success';
}
else{
    echo 'error';
}

I don't know is this the best answer to the question, but it works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM