I'm new to jquery, especially datatables. I load the data recieved from ajax call response to table as follows:
$(document).ready(function() {
$("#reservation").on("change", sendDate);
});
function LoadResponse(data) {
var table = $("#example2 > tbody");
table.empty();
table.html('');
var rows = data.split(/[@]/);
$("#dvCSV").html('');
//there are null before the first /@/
for (var i = 1;i<rows.length;i++) {
var row = "<tr>";
var cells = rows[i].split(", ");
var cell = "";
for (var j = 0; j < cells.length; j++) {
cell = cell + "<td>"+cells[j]+"</td>";
}
row = row+cell+"</tr>";
table.append(row);
}
$(function () {
$('#example2').DataTable().fnClearTable();
$('#example2').DataTable({
"destroy":true,
"dom": 'itp',
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false
});
;
console.log(table);})
};
function sendDate() {
var formData = new FormData($("#upload-file-form")[0]);
$.ajax({
url: "/sendDate",
type: "POST",
data: formData,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
beforeSend: function (){
// location.reload(false);
// $('#example2').DataTable().fnClearTable();
},
success: function (data) {
// Handle upload success
// location.reload(false);
alert("Date send to server: "+data+". date range:"+formData.get("dateRange"));
LoadResponse(data);
},
error: function (error) {
// Handle upload error
}
});
}
The code works fine for first request. However after user do another request, and then server give response, the table won't load the new data. Instead it's still use the first data received on the client-side. I can guarantee the data is received, as it seen on alert("date send to server: ").
I have tried many ways and neither of them working, including:
table.empty();
table.html('');emptying the tbody
$("#dvCSV").html('');Reload the page. This will make table lost the data from the first time.
location.reload(false);And this.
$('#example2').DataTable().fnClearTable();This will load the new data, but just temporary. Any action done to to the table will bring it back to old data. For example action on pagination, show entries, etc.
And here is my table html:
<div class="box-body">
<table id="example2" class="table table-bordered table-hover">
<thead>
<tr>
<th>MSISDN</th>
<th>Action</th>
<th>Filename</th>
<th>Date Uploaded</th>
<th>Status</th>
<th>Status Message</th>
</tr>
</thead>
<tbody id="dvCSV">
</tbody>
<tfoot>
<tr>
<th>MSISDN</th>
<th>Action</th>
<th>Filename</th>
<th>Date Uploaded</th>
<th>Status</th>
<th>Status Message</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
Any help or idea will be greatly appreciated (: