Update table with new data from Ajax Call using Button
Update table with new data from Ajax Call using Button
Below you can find my HTML and Javascript.
I cannot provide a test case because I am serving data from my local database.
What is happening in the code leading up to the issue:
I am initializing the table with all the entries in the database. Above the table, I have a "Fresh" button that makes an Ajax call to the Python Server, filters the values, and returns entries from 3 days ago.
Where everything breaks down:
When I make an Ajax call to the server, I receive entries, but the button does not update the entries in the table. (Look at the buttons: [...])
Can someone modify my code to update the DataTable with fresh upon pressing the button?
I would happy if you would have any clarifying questions. I am backend person, and I have very limited knowledge in JS, Html, and Datatables
Thank you in an advance
{% extends "base.html" %}
{% block content %}
<table id="data" class="table table-striped">
<thead>
<tr>
<th> </th>
<th>Summary</th>
<th>Media Outlet</th>
<th>Category</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
{% endblock %}
{% block scripts %}
<script>
/* Formatting function for row details - modify as you need */
function format ( d ) {
// show nothing if there is no name
if (!(d.Name)) {d.Name = ''}
// `d` is the original data object for the row
return '<table class="table">'+
'<tr>'+
'<td>Name:</td>'+
'<td>'+d.Name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Email:</td>'+
'<td>'+d.Email+'</td>'+
'</tr>'+
'<tr>'+
'<td>Query:</td>'+
'<td>'+d.Query+'</td>'+
'</tr>'+
'<tr>'+
'<td>Requirements:</td>'+
'<td>'+d.Requirements+'</td>'+
'</tr>'+
'<tr>'+
'<td>Deadline:</td>'+
'<td>'+d.Deadline+'</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function () {
var table = $('#data').DataTable({
ajax: '/api/serveHaros',
serverSide: true,
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{data: 'Summary', orderable: false},
{data: 'MediaOutlet'},
{data: 'Category'},
{data: 'Date'}
],
// button calls for the "fresh" data from in the /api/serveHaros
// but this call does not update the "table"
dom: 'Bfrtip',
buttons: [
{
text: 'Fresh',
action: function ( ) {
$.ajax({
url: '/api/serveHaros',
type: 'GET',
dataType: "json",
data : {"fresh": "fresh"}
});
}
}]
});
// Add event listener for opening and closing details
$('#data tbody').on('click', 'tr td.details-control', function () {
var table = $('#data').DataTable();
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
tr.removeClass( 'details' );
row.child.hide();
}
else {
// Open this row
tr.addClass( 'details' );
row.child( format(row.data()) ).show();
}
} );
</script>
{% endblock %}