How to Reorder row Data Table with Drag And Drop

Hello everyone i want to share how to reorder row data table through drag and drop and update data to server.

First you need embed this js & css

// js
https://code.jquery.com/jquery-3.5.1.js

https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js
https://cdn.datatables.net/rowreorder/1.2.7/js/dataTables.rowReorder.min.js
// css
https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css

https://cdn.datatables.net/rowreorder/1.2.7/css/rowReorder.dataTables.min.css

Next add paramrowReorder to DataTable

dataSrc is mean field you wanna to order
selector is mean area when you drag and drop

var dataTable = $('#data-table').DataTable( {      rowReorder: {
dataSrc: 'question_order',
selector: 'tr'
}
});

Next you need add DT_RowId to your response data table, the goal is get row ID when you move it.

{
"data": [
{
"country": "Indonesia",
"DT_RowId": "row_7",
},
{
"country": "Singapore",
"DT_RowId": "row_8",
},
]
}

Next Add event can listen when user drag and drop

row-reorder event can be listened for and an action taken when it is triggered.

dataTable.on( 'row-reorder', function ( e, diff, edit ) {
for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
// get id row
let idQ = diff[i].node.id;
let idNewQ = idQ.replace("row_", "");
// get position
let position = diff[i].newPosition+1;
//call funnction to update data
updateOrder(idNewQ, position);
}
} );

and create function to update it

var url = "https://domain.com"
function updateOrder(idQuestion, order){
$.get(url + '/updateOrder/', { question_id: idQuestion, order: order } )
.done(function( data ) {
console.log(data);
});
}

Final Step create route to update data in server side this example using PHP Phalcon Framework

public function updateOrderAction(){
$idQuestion = $this->request->getQuery('question_id');
$order = $this->request->getQuery('order');
$question = Questions::findFirst($idQuestion);
$question->question_order = $order;
$question->updated_at = $this->now();
$data = $question->update();
$response = new Response();
$response->setJsonContent([
'code' => ($data == true) ? '200' : '500',
'status' => ($data == true) ? 'Success Update Data' : 'Failed Update Data'
]);
return $response->send();}

Finally it’s over, i hope this tutorial can help anyone :)

If there are questions do not hesitate, comment below bye.