I have a datatable and am fetching the data from an api. Now i have the status like active,inactive if the flag is active then i need to show in the datatble else i should not show the expired one.Here is my fiddle. In this fiddle am showing the active and inactive both. but i want to show only the active status.
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Status</th>
<th>Message</th>
<th>Details</th>
</tr>
</thead>
</table>
SCRIPT:
$(document).ready(function() {
$('#example').DataTable({
"processing" : true,
"ajax" : {
"url" : "https://api.myjson.com/bins/12uwp2",
dataSrc : ''
},
"columns" : [ {
"data" : "name"
}, {
"data" : "email"
}, {
"data" : "subject"
}, {
"data" : "status"
},{
"data" : "message"
},
{
"mData": "Details",
"mRender": function (data, type, row) {
return "<a class='delete' data-id=" + row.id + " href='/Details/" + row.id + "'>Delete</a>";
}
}]
});
$(document).on("click", ".delete", function(e) {
e.preventDefault()
alert("Delete button clicked for Row number " + $(this).data("id"))
})
});
How to do this. Can anyone help me how to do.
The use case is: Manipulate the data returned from the server
$('#example').DataTable({
"ajax" : {
"url" : "https://api.myjson.com/bins/12uwp2",
"dataSrc": function ( json ) {
return json.filter(function(item){
return item.status=="active";
});
}
}
});
The key is to use dataSrc properly for data manipulation.
As a function - As a function it takes a single parameter, the JSON
returned from the server, which can be manipulated as required. The
returned value from the function is what will be used by DataTables as
the data source for the table.
I recommend to remove the processing property from DataTable initialization object since there is no heavy processing step anymore.
Docs
Load data for the table's content from an Ajax source - Examples
Live Example - JSFiddle
Clean code example using a separate filter function - JSFiddle
Related
I have some sort of
[
{
"selectionId":1,
"selectionDate":"101662",
"selectedBy":"ABC",
"eximPanNo":222,
"eximPanName":"DEF",
"eximPanNameEng":"KKK",
"eximPanAddress":null,
"eximPanAddressEng":null,
"eximPanPhone":12334566,
"selectionType":"G",
"consignmentNo":0,
"consignmentDate":"2098",
"productName":"LLL",
"selectionFromDate":"2019",
"selectionToDate":"2090",
"agentNo":123,
"selectionStatus":"I",
"entryBy":"PCS",
"entryDate":"2018-11-22 11:46:02",
"rStatus":"F",
"custOfficeId":1,
"selectionAudit":[
{
"audGrpId":1,
"selectionId":1,
"assignFromDate":"2075-08-03",
"assignToDate":"2075-08-19",
"entryBy":"1",
"rStatus":"1"
}
]
}
]
How can i show this selectionAudi.audGrpId data in dataTable when called from AJAX?
Here the Api is called through AJAX.
var table = $('#nepal').DataTable({
"processing" : true,
"ajax" : {
"url" : A_PAGE_CONTEXT_PATH + "/form/api/getAllSelectionAudit/all",
dataSrc : ''
},
"columns" : [ {
"data" : "selectionId"
}, {
"data" : "selectionDate"
}, {
"data" : "selectedBy"
}, {
"data" : "eximPanNo"
} ]
});
But when I add "data":"selectionAudi.audGrpId" then the datatable shows error like :
The code for table is:
<table id="nepal" class="table table-bodered">
<thead>
<tr>
<th>Selection No</th>
<th>SelectionDate</th>
<th>SelectedBy</th>
<th>PanEximNumber</th>
<th>AudiGroupID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
How can i show the inner Json data into datatable?I am not able to see what is the real solution.
Your problem is that selectionAudit is an array with one object that contains the audGrpId property, so writing just selectionAudi.audGrpId is what's throwing this Error, because it's trying to access the audGrpId property in the array.
What you need is to write selectionAudit[0].audGrpId to access the right property.
This is how should be your code:
var table = $('#nepal').DataTable({
"processing" : true,
"ajax" : {
"url" : A_PAGE_CONTEXT_PATH + "/form/api/getAllSelectionAudit/all",
dataSrc : ''
},
"columns" : [ {
"data" : "selectionId"
}, {
"data" : "selectionDate"
}, {
"data" : "selectedBy"
}, {
"data" : "eximPanNo"
}, {
"data" : "selectionAudit[0].audGrpId"
]
});
Note:
This assumes selectionAudit is an array and it's always filled with this object.
You can follow the way I usually do it not server side processing of datatable.
Suppose you HTML page from where you are making API calls -
<!-- Button to make API request -->
<button id="btnAPIRequest">API Request</button>
<!-- API response div -->
<div id="responseAPI"></div>
Call the API request through AJAX GET method and add below javascript code in bottom of your HTML page -
<script>
$("#btnAPIRequest").click(function(){
$.ajax({
type: "GET",
url: "Your/url/to/page.php",
data: 'if you have any data else blank',
dataType: 'json',
success: function(data){
if(data.success){
$("#responseAPI").html(data.message);
// Initialize datatable here
}
else{
$("#responseAPI").html(data.message);
}
}
});
});
</script>
Now in your php page where you actually calls the API and decode the json response -
<?php
// Load the reuiqred library
// Make API request
// Get the resonse in json
$response = '[{"selectionId":1,..."selectionAudit":[{"audGrpId":1,..."rStatus":"1"}]}]';
// Decode the json response
$decoded_data = json_decode($response);
// Get your html table
$msg = '
<table>
<thead>
<tr>
<th>Selection No</th>
<th>SelectionDate</th>
<th>SelectedBy</th>
<th>PanEximNumber</th>
<th>AudiGroupID</th>
</tr>
</thead>
<tbody>
';
// Table body data
foreach($decoded_data as $data){
$msg .= '
<tr>
<td>'.$data[0].'</td>
<td>'.$data[2].'</td>
<td>'.$data[3].'</td>
<td>'.$data[4].'</td>
';
// I think here you got stuck when extracting from multidimensional array
foreach($data[n] as $audi_data){
$msg .= '<td>'.$audi_data[i].'</td>';
}
$msg .= '</tr>';
}
$msg .= '</tbody></table>';
// For success respone
// encode this value in json and ajax response will handle this as per return datatype option
echo json_encode(array('success'=>true, 'message'=>$msg));
// Similarly for failed response
echo json_encode(array('success'=>true, 'message'=>$msg));
?>
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.
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.
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
}
]
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/