Datatable make cell clickable with href included in json itself - javascript

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.

Related

How do I perform a check on each value of a particular column in jQuery datatable?

I am using jquery datatable plugin for tables. I want to perform a check on each value in a column of my choice. How can I do that?
I have tried this but it performs the check on all the values present in the datatable. Is there a way to do this for values in a particular column and not the entire datatable values?
Here's the HTML
<table id="example">
<thead>
<tr>
<th>id</th>
<th>Currency</th>
<th>Lots</th>
</tr>
</thead>
</table>
Here's the Javascript
var table = $('#example').DataTable({
"bPaginate": false,
"bInfo" : false,
"columns": [
{"data": "id"},
{"data": "currency"},
{"data": "lots"}
]
});
table.cells().every( function () {
if ( this.data() > 5000 ) {
$(this.node()).addClass( 'warning' );
}
} );
I want all values in the lots column that are greater than 5000 to have class 'warning'.
I think you can use column().nodes(), as described here in the docs:
https://datatables.net/reference/api/column().nodes()
table.column(1).nodes().each( function () {
if ( this.data() > 5000 ) {
$(this.node()).addClass( 'warning' );
}
} );

Datatables json data displaying all data on one line

I am trying to setup datatables to read my json API to display data in a table. Currently it is outputting all of the object contents into one line instead of looping it like a table should be displayed.
My jsfiddle
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Blocks</th>
<th>Amount</th>
<th>Date</th>
</tr>
</thead>
</table>
JS
$(document).ready(function() {
$('#example').DataTable({
"processing" : true,
"ajax" : {
"url" : "https://zelcash.voidr.net/api/payments",
dataSrc : ''
},
"columns" : [ {
"data" : "payments.[].blocks.[]"
}, {
"data" : "payments.[].amounts.t1XHpNtYY2N3EMDRoX9RM2hq4DWWPZSmawJ"
}, {
"data" : "payments.[].time"
}]
});
});
You need an endpoint to return only an array, because this endpoint https://zelcash.voidr.net/api/payments return some objects.
You can check the datatables documentation:
https://datatables.net/examples/data_sources/ajax in this example the ajax url is https://datatables.net/examples/ajax/data/arrays.txt and this return an array.

datatables refresh not working but recieve correct json

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();
}
},

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');
}
});

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
}
]

Categories