Populate datatable with custom nested response - javascript

I am very new to data tables. And I need to populate data table with custom response other than default data table response.
please see this fiddle. It is working fine with simple response , BUT now I need to populate data table with more complex response. Below is my code.
HTML
<table id="table" class="display responsive nowrap" cellspacing="0" width="100%">
<thead style="background-color:#303641;color:#fff;">
<tr>
<th>id</th>
<th>number</th>
<th>maxDate</th>
<th>minDate</th>
<th>number2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JAVASCRIPT
$(document).ready(function() {
var result = '{"msg":"success","code":"200","status":null,"data":[{"id":3663101,"lstImeis":[{"number":"18966399926043","maxDate":"2017-08-24 22:08:58.0","minDate":"2017-08-24 22:08:58.0"},{"number":"22418344742097","maxDate":"2017-08-24 18:08:56.0","minDate":"2017-08-24 18:08:56.0"}],"number2":789},{"id":3665337,"lstImeis":[{"number":"32756451080799","maxDate":"2017-08-24 21:09:38.0","minDate":"2017-08-24 21:09:38.0"},{"number":"42540009239622","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"}],"number2":456}],"draw":0,"limit":0,"recordsFiltered":0,"recordsTotal":0}';
var json = JSON.parse(result);
var tableData = json.data;
$('#table').DataTable({
"processing": true,
"serverSide": false,
"bFilter": false,
"aaData": tableData,
"aoColumns": [{
"mData": "id"
}, {
"mData": "number"
}, {
"mData": "maxDate"
}, {
"mData": "minDate"
}, {
"mData": "number2"
}]
});
});
With this JSON response, I am unable to populate the required data in data table. I have created this fiddle as well.
I have studied this link as well, but I dopnt understand how to manage nested response in data table.
Any idea, how to populate this data into data table. ? OR any good reference ?

OK, so after some help from google, I manage to show the correct response, I used the follwoiung java script code to populate my data into data table.
$(document).ready(function () {
var result = '{"msg":"success","code":"200","status":null,"data":[{"id":3663101,"lstImeis":[{"number":"18966399926043","maxDate":"2017-08-24 22:08:58.0","minDate":"2017-08-24 22:08:58.0"},{"number":"22418344742097","maxDate":"2017-08-24 18:08:56.0","minDate":"2017-08-24 18:08:56.0"}],"number2":789},{"id":3665337,"lstImeis":[{"number":"32756451080799","maxDate":"2017-08-24 21:09:38.0","minDate":"2017-08-24 21:09:38.0"},{"number":"42540009239622","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"}],"number2":456}],"draw":0,"limit":0,"recordsFiltered":0,"recordsTotal":0}';
var json = JSON.parse(result);
var tableData = json.data;
$('#table').DataTable({
"processing": true,
"serverSide": false,
"bFilter": false,
"aaData": tableData,
"aoColumns": [
{ "mData": "id" },
{ "mData": "lstImeis.0.number" },
{ "mData": "lstImeis.0.maxDate" },
{ "mData": "lstImeis.0.minDate" },
{ "mData": "number2" }
],
});
});
I hope it will help some one else !!

Related

How to use datatables in ajax

I want to try pagination using datatables.net via ajax.
I have 2 input fields which sends start date and end date and following is the table structure
<table class="table table-hover" id="example">
<thead>
<tr>
<th>Loan ID</th>
<th>Date</th>
<th>Loan Amount</th>
<th>Loan Type</th>
</tr>
</thead>
<tbody id="amount"></tbody></table>
when the button is clicked,I am calling this function
$('#recv').click(function(){
var fromDate=$('#from').val();
var toDate=$('#to').val();
var test=$.ajax({
type: "GET",
url: "/project/getDetails",
data:{"fromDate":fromDate,"toDate":toDate},
dataType:"json",async:false
}).responseText;
var result = eval('('+test+')');
$('#example').dataTable( {
"bServerSide": true,
"sAjaxSource": result,
"bProcessing": true,
"aoColumns": [
{ "sName": "Loan_ID",
"bSearchable": false,
"bSortable": false
},
{ "sName": "Date" },
{ "sName": "Loan_Amount" },
{ "sName": "Loan_Type" }
]
} );
When Ever I click on the button then I get error in alert box saying datatables warning id=example ajax error
Can anybody please tell me how to solve?
Let datatables take care of the ajax call:
var oTable = $('#example').dataTable( {
"bServerSide": true,
"iDeferLoading": 1,
"sAjaxSource": "/project/getDetails",
"fnServerParams": function (aoData) {
aoData.push({ "name": "fromDate", "value": $('#from').val() });
aoData.push({ "name": "toDate", "value": $('#to').val() });
},
"bProcessing": true,
"aoColumns": [
{ "sName": "Loan_ID",
"bSearchable": false,
"bSortable": false
},
{ "sName": "Date" },
{ "sName": "Loan_Amount" },
{ "sName": "Loan_Type" }
]
} );
$('#recv').click(function(){
oTable.fnDraw();
});
Points to note:
fnServerParams this passes your start & end date to the
getDetails function
iDeferLoading - prevent table population on page load
fnDraw() populates the datatable from your click event

how to get the inner html value from Datatable cell

I am newbie to DataTable. here I am trying to get the of first cell value of a row when I click the viewlink associated with the row, instead of the value I am getting [object object].
heres my code
$(document).ready(function() {
// Delete a record
$('#example').on('click', 'a.editor_view', function (e) {
e.preventDefault();
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
aData = oTable.fnGetData($(this).parents('tr')[0]);
alert(aData);
} );
// DataTables init
var oTable=$('#example').dataTable( {
"sDom": "Tfrtip",
"sAjaxSource": "php/browsers.php",
"aoColumns": [
{ "mData": "browser" },
{ "mData": "engine" },
{ "mData": "platform" },
{ "mData": "grade", "sClass": "center" },
{
"mData": null,
"sClass": "center",
"sDefaultContent": 'view / Delete'
}
]
} );
} );
HTML Table:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">
<thead>
<tr>
<th width="30%">Browser</th>
<th width="20%">Rendering engine</th>
<th width="20%">Platform(s)</th>
<th width="14%">CSS grade</th>
<th width="16%">Admin</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Browser</th>
<th>Rendering engine</th>
<th>Platform(s)</th>
<th>CSS grade</th>
<th>Admin</th>
</tr>
</tfoot>
Now when I Click on the view I need to Navigate to another page with the id like
view.php?id=125
Thank you
$('#example').on('click', 'a.editor_view', function (e) {
e.preventDefault();
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
aData = oTable.fnGetData(rowIndex,0);
alert(aData);
} );
From the api docs:
fnGetData
Input parameters:
{int|node}: A TR row node, TD/TH cell node or an integer. If given as a TR node then the data source for the whole row will be returned. If given as a TD/TH cell node then iCol will be automatically calculated and the data for the cell returned. If given as an integer, then this is treated as the aoData internal data index for the row (see fnGetPosition) and the data for that row used.
{int}: Optional column index that you want the data of.
Assuming your first row is your id, would you want to include the links in your dataTable initializer like this?
$(document).ready(function () {
var oTable = $('#example').dataTable({
"aoColumnDefs": [{
"fnRender": function (oObj) {
var id = oObj.aData[0];
var links = [
'View',
'Delete'];
return links.join(' / ');
},
"sClass": "center",
"aTargets": [4]
}, {
"sClass": "center",
"aTargets": [3]
}]
});
});
see: http://jsfiddle.net/9De6w/

JS dataTable plugin: handling json format other than standard datatable format

I am new to Datatables and trying to figure out this problem.
I have a server which oupts json in certain format(see below).I cant change that on server side.
**Note: I am using link http://www.json-generator.com/j/cftupHnpbC?indent=4 to emulate my server response just for checking.
I have 2 problems
Since My json response doesn't have aaData: thing required by dataTable, I cant seem to initiliaze it.
Even if I add aaData: by hand to json just for checking, dataTable cant count total records.How I can set that manually ?Since I cant change output from server.
JSBIN LINK:
http://live.datatables.net/dasuyaf/1/edit
HTML:
<table id="example" class="display" width="100%">
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>Name</th>
<th>Text</th>
</tr>
</thead>
<tbody></tbody>
</table>
JS:
$(document).ready( function () {
var table = $('#example').dataTable({
"sAjaxSource": "http://www.json-generator.com/j/cftupHnpbC?indent=4",
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
My Server Output: (cant change this)
[
{
"text": "Some text",
"name": "somedata",
"id": "89"
},
{
"text": "Some text",
"name": "somedata",
"id": "2"
},
{
"text": "Some text",
"name": "somedata",
"id": "12"
}
]
I suppose you could just request that JSON yourself, make an object out of it and pass it to your dataTable.
var aaData;
var table;
$(document).ready( function () {
$.ajax({
url: 'http://www.json-generator.com/j/cftupHnpbC?indent=4'
}).done(function(data){
aaData = data;
table = $('#example').dataTable({
"aaData": aaData,
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
} );
I removed bServerSide - I don't think there's any way you can make use of it if you can't change your server response. Also removed sServerMethod.

DataTables warning (table id = 'example'): Requested unknown parameter '0' from the data source for row 0

i am very new to javascript and jquery and using data table to show server data. i am using below code.
$(document).ready(function () {
$("#example").dataTable({
"bProcessing": true,
"sAjaxSource": "/admin/vskuStatusUid?uploadId=" + $('#UID').val(),
"aoColumns": [{
"mData": "uid"
}, {
"mData": "vcode"
}, {
"mData": "vsku"
}, {
"mData": "timeStamp"
}, {
"mData": "state"
}, {
"mData": "counter"
}]
});
});
and my ajax response looks like below
{
"aaData": [
{
"uid": "UID0000007017",
"vcode": "927ead",
"vsku": "Prateek1000",
"timeStamp": 1391158258658,
"state": "VENDOR_PRODUCT_PERSISTENCE_COMPLETED",
"counter": 2
},
{
"uid": "UID0000007017",
"vcode": "927ead",
"vsku": "Prateek5000",
"timeStamp": 1391158258881,
"state": "VENDOR_PRODUCT_PERSISTENCE_COMPLETED",
"counter": 3
}
]
}
and my hmtl code is below
<table id="example">
<thead>
<tr>
<th>Upload Id</th>
<th >Vcode</th>
<th>Vsku</th>
<th>Timestamp</th>
<th>State</th>
<th>counter</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
can someone help me out here.
i have checked other answer related to this question and mostly all were indicating the problem might be difference in thead total column and mdata.
you dont need to write the columns in the html, dataTable does it for you. the only html you need is <table id="example"></table>
i think there error is the you insert data partially or trying to get data from unexisted row in the table.
here is a possible fix :
after you grab the data you got and parse it to object. you can do something like this:
var table = $("#example").dataTable({
"bProcessing": true,
"sAjaxSource": "/admin/vskuStatusUid?uploadId=" + $('#UID').val(),
"aoColumns": [{
"mData": "uid"
}, {
"mData": "vcode"
}, {
"mData": "vsku"
}, {
"mData": "timeStamp"
}, {
"mData": "state"
}, {
"mData": "counter"
}]
});
for (var i=0; i< ParsedObject.length; i++) {
var temp_item = ParsedObject[i]; //new row data
table.fnAddData(temp_item.uid, temp_item.vcode, temp_item.vsku, temp_item.timeStamp, temp_item.state, temp_item.counter); //adds new row to datatable
}

Trying to insert JSON data into a datatable widget

I have a Java Web Project where I have a GET endpoint that I am hitting to retrieve JSON data. Firebug shows I am getting the JSON data in the form
[{"id":7,"serial":"7bc530","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":8,"serial":"4a18d27","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":9,"serial":"f30ef","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":10,"serial":"9e6d","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":11,"serial":"4d8665a3","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":12,"serial":"4fe1457","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null}]
On the HTML side I have this,
<table id="table_id">
<thead>
<tr>
<th>id</th>
<th>serial</th>
<th>randomDouble</th>
<th>randomDouble2</th>
<th>randomDouble3</th>
<th>date</th>
<th>removed</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is what I have on the javascript side, I found another post from someone on here with this format that worked for them.
$(document).ready(function() {
var Table = $("#table_id").dataTable({
"bFilter":false,
"bPaginate":false,
"bProcessing": true,
"bServerSide":true,
"bInfo":false,
"sAjaxSource": ApiUrl(),
"fnServerData": function (sSource, aoData, fnCallback){
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
The table is displaying the columns, but it isn't pulling in the data. As I said, I did verify that the JSON data is getting sent to the webpage through Firebug -- through the GET request this is making.
I find datatables to be extremely confusing and I can't get this JSON to actually populate...
Any assistance would be very appreciated.
Edit:
I tried this,
var Table = $("#table_id").dataTable({
"bFilter":false,
"bPaginate":false,
"bProcessing": true,
"bServerSide":true,
"bInfo":false,
"sAjaxSource": ApiUrl(),
"sAjaxDataProp": ""
});
This should work for server side:
var Table = $("#table_id").dataTable({
"bFilter":false,
"bPaginate":false,
"bProcessing": true,
"bServerSide":true,
"bInfo":false,
"aoColumns": [
{ "mData": "id" },
{ "mData": "serial" },
{ "mData": "randomDouble" },
{ "mData": "randomDouble2" },
{ "mData": "randomDouble3" },
{ "mData": "date" },
{ "mData": "removed" }
],
"sAjaxSource": "url",
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
map = {}
map["aaData"] = json
fnCallback(map)
} );
}
});
UPDATE regarding last comment:
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
$.getJSON('second_json_url', function(secondjson) {
$.each(secondjson, function(index, object) {
json[index].serial = secondjson[index].name
})
map = {}
map["aaData"] = json
fnCallback(map)
})
});
}
You can read from an arbitrary data source. Check out the documentation below (found here). This works for server-side processing and ajax data sources.
Additionally, it is possible to set sAjaxDataProp to be an empty
string, which results in DataTables treating the given data source as
the table data array (rather than as property of an object).

Categories