Reputation: 6110
I have table that is already displayed on the screen. If user added new row or edit existing row then new set of data will be returned with the ajax. Once data is retrieved I want to clear the existing records from tbody
and refresh/reload dataTable
. Here is example of my code:
var statusData = {
479664: {
"author": "JH2423",
"up_to": "09/30/2017",
"status": "Closed",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Slow",
"status_id": "479664"
},
479665: {
"author": "KK2342",
"up_to": "09/30/2017",
"status": "Approved",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Close",
"status_id": "479664"
},
479666: {
"author": "DD7822",
"up_to": "09/30/2017",
"status": "Close",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Process",
"status_id": "479666"
},
479667: {
"author": "YU8343",
"up_to": "09/30/2017",
"status": "Declined",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Warrning",
"status_id": "479667"
},
479668: {
"author": "MMSD3",
"up_to": "09/30/2017",
"status": "Participating",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Approved",
"status_id": "479668"
}
};
buildDataTable('tbl-status', false, 2, false, true, true, []);
function buildDataTable(tblID, lengthChange, pageLen, searchBar, infoSection, pagingInfo, arrOrder) {
var table = $("#" + tblID),
arrSort = [];
if (arrOrder.length) {
arrSort.push(arrOrder); // arrOrder example: [1, "desc"] or [4, "asc"]. First element is column (first col starts from 0) and second is order by direction.
}
$(table).DataTable({
lengthChange: lengthChange,
pageLength: pageLen,
lengthMenu: [
[10, 15, 20, 25, 50, -1],
[10, 15, 20, 25, 50, "All"]
],
order: arrSort,
searching: searchBar,
info: infoSection,
paging: pagingInfo
});
}
$("#load").on("click", function() {
var container = $("#status-container"), // Clear out existing table.
table = $("<table>").addClass("table").prop("id", "tbl-status"),
thead = $("<thead><tr><th>Reason</th><th>As Of</th><th>Up To</th><th>Author</th><th>Date</th><th>Status</th><th class='text-center'>Status</th></tr></thead>"),
tbody = $("<tbody>");
if ($.isEmptyObject(statusData)) {
var tr = $('<tr><td colspan="7">No records were found.</td></tr>');
tbody.append(tr);
} else {
for (key in statusData) {
var btnName = statusData[key].current == true ? "Change" : "Edit";
var tr = $('<tr>');
tbody.append(tr);
tr.append($('<td>').text(statusData[key].reason));
tr.append($('<td>').text(statusData[key].as_of));
tr.append($('<td>').text(statusData[key].up_to));
tr.append($('<td>').text(statusData[key].author));
tr.append($('<td>').text(statusData[key].date));
tr.append($('<td>').text(statusData[key].status));
tr.append($('<td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="' + statusData[key].status_id + '" data-current="' + statusData[key].current + '"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> ' + btnName + '</button></td>'));
}
}
$("#tbl-agency-status").remove(); // Remove existing table.
table.append([thead, tbody]);
container.append(table);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.0/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.0/js/buttons.html5.min.js"></script>
<button type="button" name="load" id="load">Load New Data</button>
<div class="card mt-4">
<div class="card-header card-bg-custom">
<h5 class="text-center">Status</h5>
</div>
<div class="card-body">
<div class="table-responsive" id="status-container">
<table class="table" id="tbl-status">
<thead>
<tr>
<th>Reason</th>
<th>As Of</th>
<th>Up To</th>
<th>Author</th>
<th>Date</th>
<th>Status</th>
<th class="text-center">Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Failure</td>
<td>09/11/2019</td>
<td>10/31/2019</td>
<td>System</td>
<td>10/01/2019</td>
<td>Conditional</td>
<td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="505552" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Change</button></td>
</tr>
<tr>
<td>Initial</td>
<td>06/12/2017</td>
<td>09/30/2017</td>
<td>MM434</td>
<td>06/23/2017</td>
<td>Participating</td>
<td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="479664" data-current="false"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button></td>
</tr>
<tr>
<td>Reporting</td>
<td>07/11/2019</td>
<td>08/31/2019</td>
<td>System</td>
<td>10/01/2019</td>
<td>Testing</td>
<td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="505551" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
For some reason current data is not removed. I would like to remove all existing data and reload new data in the table. If anyone have suggestion please let me know.
Upvotes: 0
Views: 1553
Reputation: 1083
<script> //I usually put the script section at the end of head tag
var table_1; //declare your table var here and initialize as a datatable inside document ready below.
$(document).ready(function() {
table_1 = $('#table_1').DataTable( {
dom: "Bfrtip",
ajax: {
url: "/get-data", //path where json data will be served from. ex: get-data.php or my-data.json
type: "POST" //use POST to not have to deal with url encoding various characters
},
serverSide: true,
searchDelay: 2000, // use this to throttle ajax requests when typing in search input
processing: true, // optional visual indicator that a search has been sent to backend
lengthMenu: [ 10, 25, 50, 75, 100 ], // define per page limits. first value will be the default
buttons: [
"pageLength" // per page drop down button. i usually override/extend the default button
],
columns: [ // column definitions of json data fields
{ data: "status_id", title: "ID", width: "1%" }, // width:1% makes col width as small as possible
{ data: "status", title: "Status(hidden)", visible:false }, //visible:false hides column but allows you access to field data
{ data: "reason", title: "Reason and Status", render: function ( data, type, row ) { //render allows combining of fields into single column
return data + ' <small>('+row.status+')</small>'; // data will be reason value. row.status is how you reference status value
} },
{ data: "current", title: "Current", searchable:false }, //searchable: false set this field to not be used in search
{ data: null, title: "Button", render: function ( data, type, row ) { // use data:null if you need to render stuff in a column that does not necessarily need to be tied to a specific data value
if(row.current){
return '<button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="'+ row.status_id +'" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Change</button>';
}
else{
return '<button>Different Button</button>';
}
} },
],
rowId: 'status_id' //sets the tr row id to the value in this column. useful for DOM and other manipulation later
} );
}
</script>
<table id="table_1" class="table table-striped table-bordered table-sm" style="width:100%"></table>
<!-- If you define the title attributes in json column definitions above
then you don't need to create html table headers/footers.
Just an empty table tag will do. -->
Your ajax url will need to return data as JSON format with an array of objects:
[
{
"author": "KK2342",
"up_to": "09/30/2017",
"status": "Approved",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Close",
"status_id": "479664"
},
{
"author": "DD7822",
"up_to": "09/30/2017",
"status": "Close",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Process",
"status_id": "479666"
}
]
To get started create a file named testing.json with the above contents. Then replace table_1 ajax-url from above example to '/your_folder_path/testing.json'. This datatable should now load.
To get access to the data all you need to do is call:
table_1.data(); // datatables object
//OR
table_1.data().toArray(); // a simple array of objects with each rows data you can loop through
Docs on manipulating data for every row can be found here: https://datatables.net/reference/api/row().data()
After data has been modified you can table_1.draw() or table_1.reload() as @NawedKahn suggested - depending on your use case.
Tons of useful functionality can be found in Docs below
Everything you can do with datatables objects: https://datatables.net/reference/api/
All datatables options: https://datatables.net/reference/option/
Browse through these links before you try to build any sort of functionality, it probably already exists.
Upvotes: 1