Initialization datatable via Ajax - No data displayed - ajax

I have a datatable that I would like to initialize with an Ajax call http://url/api/v1/shocks
table.blade.php
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-striped table-md" id="table-raw-shocks" width="100%" cellspacing="0">
<thead>
<tr>
<th>Record Id</th>
<th>Count</th>
<th>Date</th>
<th>Amplitude 1 (G)</th>
<th>Amplitude 2 (G)</th>
<th>Time 1 (s)</th>
<th>Time 2 (s)</th>
<th>Freq 1 (Hz)</th>
<th>Freq 2 (Hz)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Record Id</th>
<th>Count</th>
<th>Date</th>
<th>Amplitude 1 (G)</th>
<th>Amplitude 2 (G)</th>
<th>Time 1 (s)</th>
<th>Time 2 (s)</th>
<th>Freq 1 (Hz)</th>
<th>Freq 2 (Hz)</th>
</tr>
</tfoot>
</table>
</div>
</div>
Javascript part
$(document).ready(function () {
initShocksActivityTable();
});
function initShocksActivityTable() {
var url = '{{ route("api:v1:shocks.index") }}'; //http://url/api/v1/shocks
var table = $('#table-raw-shocks-all').DataTable({
responsive: true,
responsive: {
details: {
type: "column",
target: "tr"
}
},
orderCellsTop: true,
fixedHeader: true,
dom: "Bfrtip",
buttons: ["copy", "csv", "excel", "pdf", "print"],
columnDefs: [{
sortable: true
}],
"ajax": url,
"columns": [{
"data": "attributes.record_id"
},
{
"data": "attributes.count"
},
{
"data": "attributes.date_time"
},
{
"data": "attributes.amplitude_1"
},
{
"data": "attributes.amplitude_2"
},
{
"data": "attributes.time_1"
},
{
"data": "attributes.time_2"
},
{
"data": "attributes.freq_1"
},
{
"data": "attributes.freq_2"
},
],
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
iDisplayLength: 10,
order: [
[2, "desc"]
]
});
}
My data looks like this :
Attributes contains all the necessary data that I would like to add on my datatable.
When I do that, I have no data displayed. I suspect that it is because, my data is an array ( [0], 1...)
I tried to add this piece of code (https://datatables.net/reference/option/ajax.dataSrc)
"dataSrc": "data.attributes"
But it still does not work.
I'm sure, it's something that I missed but I have some difficulties to find what is the problem to fetch correctly the data.
Could you please help me on that ? Thank

Related

Ajax filter column datatable

I'd want to display result by column dropdown filter. But after choose table doesn't update result.
My main goal is filter by "Компания" column and that selector must be on top of the table.
`
$(document).ready(function() {
var exampleDataTable = $('#example').DataTable({
responsive: true,
colReorder: true,
dom: 'Bfrtip',
buttons: [
{
extend: 'excel',
exportOptions: {
columns: ':visible'
}
},
'colvis'
],
language: {
buttons: {
colvis: 'Отображение столбцов'
},
"processing": "Подождите...",
"search": "Поиск:",
"lengthMenu": " _MENU_ ",
"info": "Показано с _START_ до _END_ записей из _TOTAL_",
"infoEmpty": "Записи с 0 до 0 из 0 записей",
"infoFiltered": "(отфильтровано из _MAX_ записей)",
"infoPostFix": "",
"loadingRecords": "Загрузка записей...",
"zeroRecords": "Записи отсутствуют.",
"emptyTable": "В таблице отсутствуют данные",
"paginate": {
"first": "Первая",
"previous": "<",
"next": ">",
"last": "Последняя"
},
"aria": {
"sortAscending": ": активировать для сортировки столбца по возрастанию",
"sortDescending": ": активировать для сортировки столбца по убыванию"
}
},
"iDisplayLength": 10,
"aLengthMenu": [[ 3, 10, 20, 50, 100 ,-1],[ 3, 10,20,50,100,"все"]],
stateSave: true,
"fnCreatedRow": function(nRow, aData, iDataIndex) {
$(nRow).attr('id', aData[0]);
},
'serverSide': 'true',
'processing': 'true',
'paging': 'true',
'order': [],
'ajax': {
'url': 'fetch_data.php',
'type': 'post',
'data': {
from_attr_1_l: from_attr_1_l,
from_attr_2_l: from_attr_2_l
},
},
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
} }); });
`
<div class="container-fluid">
<div class="row">
<div class="container">
<div class="row">
<div class="col-md-8">
<table id="example" class="table">
<thead>
<th>Id</th>
<th>Номер</th>
<th>ФИО</th>
<th>Дата</th>
<th>Срок</th>
<th>Кол-во мест</th>
<th>Метка</th>
<th>ИНН</th>
<th>Телефон</th>
<th>КПП</th>
<th>Компания</th>
<th>Адрес</th>
<th>Email</th>
<th>Ответственный</th>
<th>Партнер</th>
<th>К. телефон</th>
<th>К. email</th>
<th></th>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Id</th>
<th>Номер</th>
<th>ФИО</th>
<th>Дата</th>
<th>Срок</th>
<th>Кол-во мест</th>
<th>Метка</th>
<th>ИНН</th>
<th>Телефон</th>
<th>КПП</th>
<th>Компания</th>
<th>Адрес</th>
<th>Email</th>
<th>Ответственный</th>
<th>Партнер</th>
<th>К. телефон</th>
<th>К. email</th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
I used different solutions also from https://datatables.net/examples/api/multi_filter_select.html and https://datatables.net/forums/discussion/73081/select-dropdown-list-filter but didn't work.

DataTables warning: table id=extension - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3

DataTables warning: table id=user - Cannot reinitialise DataTable. For
more information about this error, please see
http://datatables.net/tn/3
<table id="user" class="table datatable-responsive-row-control">
<thead>
<tr>
<th>Username</th>
<th>Account</th>
<th>data CID</th>
<th>Type</th>
<?php if(!$this->session->userdata('type') == '0') { ?>
<th>Action</th>
<?php } ?>
</tr>
</thead>
<tbody>
</tbody>
</table>
$(document).ready(function () {
$('#user').DataTable({
"processing": true,
"serverSide": true,
"ajax":{
"url": "<?php echo base_url('user/use_data') ?>",
"dataType": "json",
"type": "POST",
},
"columns": [
{ "data": "name" },
{ "data": "accountid" },
{ "data": "dataid" },
{ "data": "type" },
<?php if(!$this->session->userdata('type') == '0') { ?>
{ "data": "actions" },
<?php } ?>
]
});
});

Ignited Datatable with 'if ' query

How to put a 'if' query on Ignited datatable? Here is my query:
This is my controller:
function ajaxGetCard() {
$this->load->library('Datatables');
$this->datatables->set_database('retail');
$this->datatables
->select('studEmpID, fullname, serialNumber, balance, If(status = "0", "Enable", "Disabled") as status')
->from('retail_card');
echo $this->datatables->generate();
}
This is my view:
<script type="text/javascript">
$(function() {
$('#example').DataTable( {
"bProcessing": true,
"bserverSide": true,
"ajax": "<?php echo site_url('card/ajaxGetCard'); ?>",
"columns": [
{ "data": "studEmpID" },
{ "data": "fullname" },
{ "data": "serialNumber" },
{ "data": "balance" },
{ "data": "status" },
{ "data": "actions" }
]
} );
});
</script>
<table class="table table-bordered datatable table-striped" id="example">
<thead>
<tr>
<th>ID Number</th>
<th width="30%">Name</th>
<th>Serial</th>
<th>Balance (MYR)</th>
<th>Status</th>
<td>Actions</td>
</tr>
</thead>
When I run this, I've got this error:
DataTables warning: table id=example - Ajax error. For more information about this error, please see http://datatables.net/tn/7
I already refer the given url, but still not solve the problem. If I remove the the 'if' statement in that query, everything works fine. Please help

Datatables Translation don't works

I have got a datatable using Datatables server-side. I have created and filled the table as shown below. Now I need to translate the datatable depending on the language , I found this example in the documentation :
$('#example').DataTable( {
language: {
search: "Search in table:"
}
} );
or loading translation :
$('#example').DataTable( {
language: {
url: '/localisation/fr_FR.json'
}
} );
But none of them works for me ! this is my code :
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>name</th>
<th>adress</th>
</tr>
</thead>
</table>
$(document).ready(function() {
var oTable = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "server-side-process",
},
"columns": [
{ "data": "name" },
{ "data": "adress" },
]
} );
} );
var oTable = $('#example').DataTable({
"language": {"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},
"processing": true,
"serverSide": true,
"ajax": {...
https://datatables.net/plug-ins/i18n/
Below is a working example of two datatables. One using default English and one loading French as per the documentation: https://datatables.net/reference/option/language
JSFiddle link: https://jsfiddle.net/invalidname/mro9h48u/2/
$(document).ready(function() {
var oTable = $('#example').DataTable({
"processing": true,
"serverSide": false,
"ajax": {
"url": "https://run.mocky.io/v3/b99908b5-61f9-4d41-9292-deaa510f3d93",
},
"columns": [
{ "data": "name" },
{ "data": "adress" },
]
} );
} );
$(document).ready(function() {
var oTable = $('#exampleFR').DataTable({
"processing": true,
"serverSide": false,
"ajax": {
"url": "https://run.mocky.io/v3/b99908b5-61f9-4d41-9292-deaa510f3d93",
},
"language": {
"url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/French.json"
},
"columns": [
{ "data": "name" },
{ "data": "adress" },
]
} );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<H1>
English table
</H1>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>name</th>
<th>adress</th>
</tr>
</thead>
</table>
<hr>
<hr>
<H1>
French table
</H1>
<table id="exampleFR" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>name</th>
<th>adress</th>
</tr>
</thead>
</table>

bllim/laravel4 datatables - not working

I am using Bllim Laravel for the first time.
I am not getting any error message but neither able to populate the data in datatable, I am getting the datatable but it has no data in it. Query is working fine and I can see the data in it but it doesn't get passed to Datatable or is not in the format that datatable is able to read
Posting code here:
Controller
public function listAjax() {
$posts = DB::table('newspaper')->select('id', 'no_of_pages', 'date', 'publishing_time', 'status');
return Datatables::of($posts, true)->make();}
View
<table id="newspaperList" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>No of pages</th>
<th>Date</th>
<th>Publishing time</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#newspaperList").dataTable({
"processing": true,
"serverSide": true,
"ajax": "http://localhost:88/epaperlaravel/public/ep-admin/newspaper/listajax",
"order": [[1, 'desc']],
"columnDefs": [{//this prevents errors if the data is null
"targets": "_all",
"defaultContent": ""
}],
"columns": [
//title will auto-generate th columns
{"data": "id", "title": "Id", "orderable": true, "searchable": false},
{"data": "no_of_pages", "title": "Name", "orderable": true, "searchable": true},
{"data": "date", "title": "Username", "orderable": true, "searchable": true},
{"data": "publishing_time", "title": "Email", "orderable": true, "searchable": true},
{"data": "status", "title": "Created", "orderable": true, "searchable": true},
]
});
});
Route
Route::get('ep-admin/newspaper/listajax', array('as' => 'articlesajax', 'uses' => 'NewspaperController#listAjax'));
Where i am going wrong?
This much script is needed for displaying data :
$('#dataTables-example').DataTable( {
bProcessing: true,
bServerSide: true,
dom: "Tfrtip",
sAjaxSource: "{{ URL::to('/work/showusers') }}",
aaSorting : [[ 0, "desc" ]],
"aoColumns": [
{ 'sWidth': '60px' },
{ 'sWidth': '130px', 'sClass': 'center' },
{ 'sWidth': '180px', 'sClass': 'center' },
{ 'sWidth': '60px', 'sClass': 'center' },
],
tableTools: {
sRowSelect: "os",
aButtons: [
{ sExtends: "editor_create", editor: editor },
{ sExtends: "editor_edit", editor: editor },
{ sExtends: "editor_remove", editor: editor }
]
},
language: {
processing: "Traitement en cours...",
search: "Rechercher :",
lengthMenu: "Afficher _MENU_ éléments",
info: "Affichage de l'élement _START_ à _END_ sur _TOTAL_ éléments",
infoEmpty: "Affichage de l'élement 0 à 0 sur 0 éléments",
infoFiltered: "(filtré de _MAX_ éléments au total)",
infoPostFix: "",
loadingRecords: "Chargement en cours...",
zeroRecords: "Aucun élément à afficher",
emptyTable: "Aucune donnée disponible dans le tableau",
paginate: {
first: "Premier",
previous: "Précédent",
next: "Suivant",
last: "Dernier"
},
aria: {
sortAscending: ": activer pour trier la colonne par ordre croissant",
sortDescending: ": activer pour trier la colonne par ordre décroissant"
}
}
} );
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Password</th>
</tr>
</tfoot>
</table>

Resources