datatables refresh not working but recieve correct json - javascript

I have an error in my code and can’t figure out, what i did wrong.
The datatable gets filled correctly and on ajax.refresh the table gets valid json-data, but the table does not reload.
HTML
<table id="monatsabschluss" class="listing">
<thead class="header">
<tr>
<th>Aufgabe</th>
<th>Status<input type="checkbox" id ="express" ></th>
</tr>
</thead>
<tbody>
Javascript
var adat = '20160606';
var kid = 7;
var table = $('#monatsabschluss').DataTable( {
"paging": false,
"info": false,
"filter": false,
"ordering": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "/management/bavabrech/fetchjobs",
"data": function ( d ) {
d.kid = kid;
d.adat = adat;
},
"dataSrc": "data",
},
"columns": [
{ "data": "description" },
{ "data": "status", className: 'statusCol' },
],
});
setInterval( function () {
table.ajax.reload( null, false );
}, 5000 );
Json
{"sEcho":1,
"success":true,
"iTotalRecords":0,
"iTotalDisplayRecords":0,
"aaData":
[{"description":"Erstellen Rentendaten",
"status":3,"id":"1"},
{"description":"Pr\u00fcfliste erstellen",
"status":4,"id":"2"},
{"description":"TEXT","status":"","id":"out_2"}]}
HTML-Output from the initial Datatable-loading
<table class="listing dataTable no-footer" id="monatsabschluss"
role="grid" style="width: 800px;">
<thead class="header">
<tr role="row">
<th class="sorting_disabled" rowspan="1" colspan="1"
style="width: 469px;">Aufgabe</th>
<th class="sorting_disabled statusCol" rowspan="1" colspan="1"
style="width: 269px;">Status<input type="checkbox" id="express">
</th>
</tr>
</thead>
<tbody class="">
<tr role="row" class="maStatusRunning">
<td>Erstellen Rentendaten</td>
<td class=" statusCol">Wird ausgeführt</td>
</tr>
<tr role="row" class="maStatusComplete">
<td>Prüfliste erstellen</td>
<td class=" statusCol">Erledigt</td>
</tr>
<tr role="row" class="odd">
<td>TEXT</td>
<td class=" statusCol"></td>
</tr>
</tbody>
</table>
I am using Datatable 1.10.7, i do not get any error messages.

Ok, I have installed all your code and dug deeper into the problem. Your issue is with your serverSide property. When that is on true, the client expects you to mirror the draw property send to the server so he know that the response he got is for the request he sent (see https://datatables.net/manual/server-side). I also saw that you are using deprecated property names in your response (aaData etc....). You have to change those, so he recognizes your draw property.
That is how the response looks on my side and how it works in my example with your code
<?php
header('Content-type: application/json');
?>
{
"success":true,
"recordsTotal":0,
"recordsFiltered":0,
"draw": <?= (int)$_GET['draw'] ?>,
"data":
[
{"description":"Erstellen Rentendaten", "status":3,"id":"1"},
{"description":"Pr\u00fcfliste erstellen", "status":4,"id":"2"},
{"description":"TEXT","status":"","id":"out_2"}
]
}
I have added mirroring the draw property (you can see that in the request url) and renamed aaData to data, iTotalRecords to recordsTotal, iTotalDisplayRecords to recordsFiltered and removed iEcho

I haven't tried your example yet, but I can tell a few javascript errors you have.
First of all your data function definition is wrong
"data": function ( d ) {
d.kid = kid,
d.adat = adat
},
The function body is no valid Javascript.
Then there are trailing commas that not every browser likes and that are invalid for json
"dataSrc": "data",
{ "data": "status", className: 'statusCol' },
and at the end of your table defintion after the columns part. Do you use an IDE? It should highlight those occurences.
I would start putting a debugger call into your data method so you can track down what happens in there.

There are few problems with your code. The most important thing to remember: always have defined all columns that come with AJAX, hide them via API.
Second thing, do not mix datatables 1.X and 2.X code. It appears to me, that your column definition is for version 2.X, wheras rest of the code is version 1.X
So:
Your columns definition is wrong. You're missing one column
"aaData": [
{ ""mData"": "description" },
{ ""mData"": "status"},
{ "sClass": "statusCol" }
],
If you would like to hide column, use bVisible parameter
{ "sName":"id", "sTitle":"Foo", "sClass":"center", "sWidth":"10%", "bSortable":"false", "bVisible": false },
I would also change the table html markup to
thead
<tr>
<th>ID</th>
<th>Aufgabe</th>
<th>Status<input type="checkbox" id="express"></th>
</tr>
tbody
<tr>
<td colspan="3">No data yet</td>
</tr>
It's always good practive, to use iniutComplete, to see if everything was ok:
"fnInitComplete": function (){
console.log("Init done");
},
And the last thing: if you have would like to have extra content inside TD cells, use cell custom renderer.
{
"mRender" : function(data, type, row){
var sb = [];
sb.push('<div class="test' + data + '" title="' + row[2] + '"> </div>');
return sb.join();
}
},

Related

Datatable make cell clickable with href included in json itself

I am using bootstrap datatable to make a simple presentation of my json. I am using this json to feed datatable :
{
"manualList":[
{
"number":"WFC2062/05",
"umtype":"PT,SI",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009686_A.pdf",
"version":"A",
"filelenght":1002357,
"urlstatus":true
},
{
"number":"WFC2062/05",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009685_B.pdf",
"version":"B",
"filelenght":6377032,
"urlstatus":true
},
{
"number":"WFC2062/06",
"umtype":"PT,SI",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009686_A.pdf",
"version":"A",
"filelenght":1002357,
"urlstatus":true
},
{
"number":"WFC2062/06",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009685_B.pdf",
"version":"B",
"filelenght":6377032,
"urlstatus":true
},
{
"number":"WFC2062/07",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/9000029228_C.pdf",
"version":"C",
"filelenght":5918430,
"urlstatus":true
},
{
"number":"WFC2062/08",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/9000029228_C.pdf",
"version":"C",
"filelenght":5918430,
"urlstatus":true
}
],
"servicetype":"vibki",
"errormessage":null,
"warning":null
}
Data is in json format and i want to show hyperlink with column number, so my aim to add a column with the text of one manualList number and hyperlink of manuaList's cdnlink. But i don't know how to refer both of them inside one column.
Here is my script that creates datatable :
$(document).ready(function() {
var link = localStorage.getItem("link_url");
var table = $('#example').DataTable( {
"ajax": {
"url": link,
"dataSrc": "manualList"
},
"columns": [
{
"data": "cdnlink",
"render" : function(data, type, row, meta){
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text()
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
},
{ "data": "lang" }
]
});
$('#example')
.removeClass( 'display' )
.addClass('table table-striped table-bordered');
} );
link_url is giving ajax response that i've mentioned above, so you can this example json to evaluate the response.
Here is simple HTML that includes datatable as example :
<div class="container">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Number</th>
<th>Language</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Number</th>
<th>Language</th>
</tr>
</tfoot>
</table></div>
I hope someone can help me, many thanks in advance for your responses!
I've checked below link to make column rendering on datatable :
https://datatables.net/examples/advanced_init/column_render.html
So, i've created one more invisible column to put cdnlink there and changed from columns to columnDefs such as :
$(document).ready(function() {
var link = localStorage.getItem("link_url");
var table = $('#example').DataTable( {
"ajax": {
"url": link,
"dataSrc": "manualList"
},
"columnDefs": [
{
"data" : "cdnlink",
"targets" : 2
}
,
{// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"data" : "number",
"render": function ( data, type, row ) {
return $('<a>')
.attr({target: "_blank",href: row.cdnlink})
.text(data)
.wrap('<div></div>')
.parent()
.html();
},
"targets": 0
},
{
"data" : "lang",
"targets" : 1
},
{ "visible": false, "targets": [ 2 ] }
]
});
$('#example')
.removeClass('display')
.addClass('table table-striped table-bordered');
} );
I've also added column in html file :
<div class="container">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Number</th>
<th>Language</th>
<th>Link</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Number</th>
<th>Language</th>
<th>Link</th>
</tr>
</tfoot>
</table></div>
Then it worked like charm.

Cannot set class for row when check box clicked

I want to set a css style to the row where checkbox is clicked but am unable to do so. The code is as follows. The code for checkbox click works fine for both the select all and individual check box. I want to get the Request ID for the selected rows and send them to the database via JSON object by post method to a php script.
Possibly the row is not getting selected.
HTML:
<table id="mytable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th><input type="checkbox" name= "check_all" id="check_all"/></th>
<th>Request ID</th>
<th>Request Date</th>
<th>Leave Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
</tr>
</thead>
</table>
javascript
$('#mytable').DataTable({
data: msg,
columns: [
{ data: 'RequestID'},
{ data: 'RequestID' },
{ data: 'RequestDate' },
{ data: 'LeaveType' },
{ data: 'LeaveStart' },
{ data: 'LeaveEnd' },
{ data: 'Status' }
],
"columnDefs": [ {
"targets": 0,
"searchable": false,
"data": "RequestID",
"render": function ( data, type, full, meta ) {
return '<input type="checkbox" class="checkBoxClass" name= "check_id[]" data-id="'+data+'" />';
},
}]
});
$("#check_all").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
$(".checkBoxClass").change(function(){
if (!$(this).prop("checked")){
$("check_all").prop("checked",false);
$('#mytable').row(this).removeClass('row_selected');
}
$('#mytable').row(this).addClass('row_selected');
});
CAUSE
There are some issues with your code:
You attach event handler directly but with jQuery DataTables only current page elements exist in DOM. Use delegated event handler instead.
You need to access row node by using $(this).closest('tr'), not $('#mytable').row(this)
Conditional statement was missing else part.
SOLUTION
Use the code below to attach delegated event handler to all checkboxes.
$("#mytable").on('change', '.checkBoxClass', function(){
if (!$(this).prop("checked")){
$("check_all").prop("checked", false);
$(this).closest('tr').removeClass('row_selected');
} else {
$(this).closest('tr').addClass('row_selected');
}
});

How to get AJAX response before sending to template using DATATABLES?

I am implementing a log tables in my admin panel and I used the datatable plugin.
I created an ajax in my datatable but I don't know how to get the response before sending to the table.
I have this in my jquery:
<script type="text/javscript">
$(document).ready(function() {
$('#log-pageview')
.on('xhr .dt', function(e, settings, json) {
$('#status').html(json.status)
})
.dataTable({
"processing": true,
"serverSide": true,
"ajax": "/secure/logs/visits.php?log_get=1"
});
});
</script>
In my HTML I have this:
<table id="log-pageview" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Log ID</th>
<th>User ID</th>
<th>IP Address</th>
<th>Date Viewed</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Log ID</th>
<th>User ID</th>
<th>IP Address</th>
<th>Date Viewed</th>
</tr>
</tfoot>
</table>
<div id="status"></div>
In my server side PHP I have this.
function get_pageview() {
$host = mysql_connect('localhost','avjunky_2','1qaz2wsx') or die(mysql_error());
mysql_set_charset('utf8', $host); //added for character encoding, made it global for functions /** added by rochelle **/
$db = mysql_select_db('avjunky_2',$host) or die(mysql_error());
$log_array = array();
$log_data = array();
$get_all_logs = mysql_query("SELECT id, logged_id, ip_address, date_viewed FROM avjunky_pageview", $host);
while($row_logs = mysql_fetch_array($get_all_logs)) {
$log_data[] = array(
'id' => $row_logs['id'],
'logged_id' => $row_logs['logged_id'],
'ip_address' => $row_logs['ip_address'],
'date_viewed' => $row_logs['date_viewed']
);
}
$total_count = count($log_data);
$log_array = array(
'draw' => 1,
'recordsTotal' => $total_count,
'recordsFiltered' => $total_count,
'data' => $log_data
);
echo json_encode($log_array);
}
if(isset($_GET['log_get'])) {
get_pageview();
}
In the server side I generated this kind of json:
{"draw":1,"recordsTotal":2,"recordsFiltered":2,"data":[{"id":"3","logged_id":"7","ip_address":"122.2.55.11","date_viewed":"2015-03-16 10:10:42"},{"id":"2","logged_id":"8","ip_address":"122.2.55.11","date_viewed":"2015-03-17 00:05:40"}]}
{
"draw":1,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
{
"id":"3",
"logged_id":"7",
"ip_address":"122.2.55.11",
"date_viewed":"2015-03-16 10:10:42"
},
{
"id":"2",
"logged_id":"8",
"ip_address":"122.2.55.11",
"date_viewed":"2015-03-17 00:05:40"
}
]
}
I don't know where did I go wrong. I checked the developer tool network tab and it seems that the ajax is not calling the URL.
In my AJAX I also tried to call the response from the URL like this.
http://mysite/admin/secure/logs/visits.php?log_get=1
But it doesn't load the data as well.
Firstly, to use xhr.dt datatables > 1.10 should be used.
Secondly, the data should be of the following structure.
{
"draw":1,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
[
"3",
"7",
"122.2.55.11",
"2015-03-16 10:10:42"
],
[
"2",
"8",
"122.2.55.11",
"2015-03-17 00:05:40"
]
]
}
Here is a demo

Displaying image on Datatable

I am using server side processing to read the database table and convert the records into Json file, and pass it to the database table to display data.
Read database and convert it into json:
code:
Route::get('banner/list/banners/json/{id}', function ()
{
$banner = DB::table('banner_creatives')->where('Id','=','53')->get();
$recordsTotal = count($banner);
$data['draw'] = 1;
$data['recordsTotal'] = $recordsTotal;
$data['recordsFiltered'] = $recordsTotal;
$data['data'] = $banner;
return Response::json($data);
});
Json output:
{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"id":1,"bId":26,"cId":53,"bName":"32_32_53.jpeg","storageType":"url","width":32,"height":32,"weight":1,"imageURL":"localhost:8000\\\/banner\\\/view\\\/32_32_53.jpeg","clickURL":"","created_at":"2015-01-26 12:32:28","updated_at":"2015-01-26 12:32:28","deleted_at":null}]}
As you can see on this json, I have the image Url that I want to display it on the table.
JavaScript code:
$(document).ready(function() {
var table = $('#banner').DataTable( {
"processing": true,
"serverSide": false,
"ajax": "banners/json/53",
"columns": [
{ "data": "id" },
{ "data": "bannerId" },
{ "data": "campaignId" },
{ "data": "bannerName" },
{ "data": "width" },
{ "data": "height" },
{ "data": "imageUrl" }
});
});
Datatable code:
<table id="banner" class="display table table-striped table-bordered table-hover dataTable no-footer" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>Banner Id</th>
<th>Campaign Id</th>
<th>Banner Name</th>
<th>Width</th>
<th>Height</th>
<th>Image/Banner</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>Banner Id</th>
<th>Campaign Id</th>
<th>Banner Name</th>
<th>Width</th>
<th>Height</th>
<th>Image/Banner</th>
</tr>
</tfoot>
</table>
On the last column it displaying the image URL but is not what i want, i want to display the usually image on the datatable using the URL, if it possible.
You can use the columns.render option to specify a callback function that can modify the data that is rendered in the column.
The callback function takes three parameters (four since 1.10.1). The first parameter is the original data for the cell (the data from the db), the second parameter is the call type (filter, display, type, or sort), and the third parameter is the full data source for the row. The function should return the string that should be rendered in the cell.
In your columns definition, add the render option to your imageUrl column definition:
{
"data": "imageUrl",
"render": function(data, type, row) {
return '<img src="'+data+'" />';
}
}
Documentation on the render option found here.
Here's my solution, hope it helps someone.
{
'targets': [15,16],
'searchable': false,
'orderable':false,
'render': function (data, type, full, meta) {
return '<img src="'+data+'" style="height:100px;width:100px;"/>';
}
},
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return '<img src="'+data+'" style="width=300px;height=300px;" />';
},
"targets": 1 // column index
}
]

binding jquery datatable gives error "Requested unknown parameter '0' from the data source for row 0"

i am creating json format for jquery datatable using jquery ,
but it gives error "DataTables warning (table id = 'tblDynamicModifierItems2'): Requested unknown parameter '0' from the data source for row 0"
my Html is
<table id="tblDynamicModifierItems" class="tblDynamicModifierItems table table-hover table-nomargin dataTable table-bordered dataTable-scroller dataTable-tools">
<tbody></tbody>
</table>
my Jquery code is
var aaData = [];
var ModifierItemCode = "1";
var Description = "10 cane rum"
aaData.push({
"ModifierItemCode": ModifierItemCode,
"ModifierItem": Description,
"Delete": "Delete"
});
var oTable = $("#tblDynamicModifierItems").dataTable({
"aaData": aaData,
"aoColumns": [{ "bVisible": false }, { "sTitle": "Description" }, null],
});
oTable.fnSort([[1, 'asc']]);
can anyOne help me solve this?
You need to make the markup right. jQuery dataTables is very sensitive to that. It is important to define the headers, <th>, so dataTables have a chance to know how many columns it should expect in each row of data.
<table id="tblDynamicModifierItems" class="tblDynamicModifierItems table table-hover table-nomargin dataTable table-bordered dataTable-scroller dataTable-tools">
<thead>
<tr>
<th>ModifierItemCode</th>
<th>ModifierItem</th>
<th>Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
Also, you must tell dataTables which part of each aaData item that should correspond to which column :
var oTable = $("#tblDynamicModifierItems").dataTable({
"aaData": aaData,
"aoColumns": [
{ mDataProp : "ModifierItemCode" },
{ mDataProp : "ModifierItem" },
{ mDataProp : "Delete" }
]
});
your code in a demo -> http://jsfiddle.net/s9Lag6mc/
Regarding your "aoColumns": [{ "bVisible": false }, { "sTitle": "Description" }, null], I am not completely sure what you are trying to do, but if you want to hide the first column, just add bVisible: false to the first aoColumns item, and so on.
As for your fnCreatedRow problem : Think about it, you are inserting an object. So instead of alert(aData[0]) (or whatever) simply
alert(aData.ModifierItemCode);
forked fiddle -> http://jsfiddle.net/0aLys2d3/

Categories