Reputation: 264
I have a problem here, I want to create a table using datatables after getting data from ajax, i have no idea to make it, here while I use append to make the table, can some one help me?
$.ajax({
type: "get",
url: "{{route('getAccount-user')}}"+"/"+user_id,
dataType: "json",
success: function(data){
if (data.length==0){
$('#list-account').append(`
<tr id="">
<td colspan="5" class="text-center">
<h5> Data not fount </h5>
</td>
</tr>
`)
}
else{
$.each(data, function(key, value) {
$('#list-account').append(`
<tr>
<td>
<input type="hidden" id="finfini_id" value="${value.finfini_account_id}">
<input type="hidden" id="connect_id" value="${value.connect_id}">
${value.fullname}
</td>
<td>
${value.month}
</td>
<td>
${value.name}
</td>
<td>
${value.debet}
</td>
<td>
${value.kredit}
</td>
<td>
${value.balance}
</td>
</tr>
`)
});
}
},
});
for the time being I made the tabs using the append function in jquery, whereas I wanted to change the tabs using datatables, I tried several codes but nothing worked and this my html code
<table id="tAccount" class="table display" style="width:100%">
<thead class="thead-dark">
<tr>
<th scope="col">Fullname</th>
<th scope="col">Month</th>
<th scope="col">Bank</th>
<th scope="col">Debet</th>
<th scope="col">Kredit</th>
<th scope="col">Balance</th>
</tr>
</thead>
<tbody id="list-account">
</tbody>
</table>
Upvotes: 0
Views: 53
Reputation: 432
You should pass object with ajax
and columns
properties to DataTable()
method. And remove the tbody
from your table:
$('#tAccount').DataTable({
ajax: "{{route('getAccount-user')}}" + '/' + user_id,
columns: [
{ data: 'fullname' },
{ data: 'month' },
{ data: 'name' },
{ data: 'debet' },
{ data: 'kredit' },
{ data: 'balance' }
]
});
<table id="tAccount" class="table display" style="width:100%">
<thead class="thead-dark">
<tr>
<th scope="col">Fullname</th>
<th scope="col">Month</th>
<th scope="col">Bank</th>
<th scope="col">Debet</th>
<th scope="col">Kredit</th>
<th scope="col">Balance</th>
</tr>
</thead>
</table>
However, you will not be able to insert those hidden inputs using this method. Creating table body on your own is much more flexible.
Your code that appends an element to DOM on every iteration is a bit inefficient. Here is slightly modified and optimized version:
$.ajax({
type: 'get',
url: "{{route('getAccount-user')}}" + '/' + user_id,
dataType: 'json',
success: function(data) {
let tbody = '';
if (data.length > 0) {
$.each(data, function(key, value) {
tbody += `
<tr>
<td>
<input type="hidden" id="finfini_id" value="${value.finfini_account_id}">
<input type="hidden" id="connect_id" value="${value.connect_id}">
${value.fullname}
</td>
<td>${value.month}</td>
<td>${value.name}</td>
<td>${value.debet}</td>
<td>${value.kredit}</td>
<td>${value.balance}</td>
</tr>
`;
});
$('#list-account').append(tbody).DataTable();
}
}
});
PS, there is no need for inserting "No data found" message. DataTable()
does this automatically if table body is empty.
Upvotes: 1