Datatables.net json data load - javascript

I am trying to load the below json data into Datatables, but I'm facing error. My web browser(chrome) successfully downloads the data, but it does not represent the data. The table shows only the name of columns but nothing. Can someone please help me?
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"Feature_ID": "4",
"Clean_Feature_Name": "Abalos Colles",
"Feature_Type": "Collis, colles",
"Feature_Type_Code": "CO",
"title": "['Arecibo radar imagery of Mars: II. Chryse-Xanthe, polar caps, and other regions']",
"author": "['Harmon, John K.', 'Nolan, Michael C.']",
"year": 2017,
"bibcode": "2017Icar..281..162H",
"pub": "Icarus"
}
}
]
}
And below is my javascript code.
$(document).ready(function() {
$('#example').DataTable( {
"ajax" : {
"url" : "http://212.201.46.76/data_final/sample_paper.json",
},
"columns" : [
{ "features" : "properties.Feature_Id" },
{ "features" : "properties.Clean_Feature_Name" },
{ "features" : "properties.Feature_Type" },
{ "features" : "properties.Feature_Type_Code" },
{ "features" : "properties.title" },
{ "features" : "properties.author" },
{ "features" : "properties.year" },
{ "features" : "properties.bibcode" },
{ "features" : "properties.pub" },
]
} );
} );
My HTML code
<body>
<button id="reload">Reload</button>
<div class="container">
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Feature_ID</th>
<th>Clean_Feature_Name</th>
<th>Feature_Type</th>
<th>Feature_Type_Code</th>
<th>Bibcode</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Pub</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Feature_ID</th>
<th>Clean_Feature_Name</th>
<th>Feature_Type</th>
<th>Feature_Type_Code</th>
<th>Bibcode</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Pub</th>
</tr>
</tfoot>
</table>
</div>
</body>

You're specifying your columns array wrong.
The columns array is where you specify a number of options in your table, on a per-column basis. There is no features option available; presumably that's why you're not seeing a table. Available values are here.
Now, you should be able to simply do this:
$(document).ready(function() {
$('#example').DataTable( {
"ajax" : {
"url" : "http://212.201.46.76/data_final/sample_paper.json",
}
});
});
as in this example (which you probably used to get started), removing your columns definition entirely. You've already specified the columns using HTML. If you need different options from the example, you need to learn to use columns correctly.
For more information on this, see this post.

Finally I found a solution.
This is how you do when the json file has different format with examples.
"dataSrc" <-- follow your json format
{ "data" : "properties.title"} <-- "data" is always "data' it's a fixed key. you should not change it whatever "dataSrc" is.
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"ajax" : {
"url": "http://212.201.46.76/data_final/sample_paper.json",
"dataSrc": "features"
},
"columns": [
{ "data" : "properties.title" },
{ "data" : "properties.author" },
{ "data" : "properties.year" },
{ "data" : "properties.bibcode" },
{ "data" : "properties.pub" }
]
});

Related

why won't jquery datatable populate?

This is driving me nuts. I have a web site that works fine. Datatable populates from a .php ajax call. I'm migrating that code to a different web site. Identical ajax call but this time won't populate!
Here is the js of the one that works:
$('#divTable').DataTable({
"ajax": "screen_highYield.php",
"columns": [
{ "data": "Symbol" },
{ "data": "CompanyName" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" }
]
});
And the html:
<div id="highYieldDiv">
<table id="divTable" class="display" style="width:100%">
<thead>
<tr>
<th>Symbol</th>
<th>Company Name</th>
<th>Ex-Div<br>Date</th>
<th>Dividend</th>
<th>Div<br>Yield%</th>
<th>Div<br>Frequency</th>
<th>Pay Date</th>
</tr>
</thead>
</table>
</div>
Here is the js of the one that fails:
$('#divTable').DataTable({
"ajax": {
url: "screen_highYield.php",
"done": function() {
alert('done');
},
"success": function(data) {
console.log(JSON.stringify(data));
},
"error": function(jqXHR, textStatus, errorThrown) {
alert('error');
},
"initComplete": function(settings, json) {
alert( 'DataTables has finished its initialisation.' );
}
},
"columns": [
{ "data": "Symbol" },
{ "data": "CompanyName" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" }
]
});
And the html:
<div id="highYieldDiv">
<table id="divTable" class="display" style="width:100%">
<thead>
<tr>
<th>Symbol</th>
<th>Company Name</th>
<th>Ex-Div<br>Date</th>
<th>Dividend</th>
<th>Div<br>Yield%</th>
<th>Div<br>Frequency</th>
<th>Pay Date</th>
</tr>
</thead>
</table>
</div>
I added the "done", "success", "error", and "initComplete" in an attempt to figure out what's wrong. Nothing was output to the console. Then I moved the js to the $(document).ready function and then I got the "success" to trigger. (Didn't have to do that in the one that works.) I took the json it output and verified it was valid json using jsonlint. The table just says Loading...
I don't understand why it works one place an not another. These black boxes are so mysterious and difficult to debug. Ideas?

Filling a Datatable with a JSON from an API

<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>hair_color</th>
<th>skin_color</th>
<th>gender</th>
</tr>
</thead>
</table>
</body>
This is my table HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable( {
ajax: {
url: 'https://swapi.co/api/people/1/',
dataSrc: ''
},
columns: [
{ data: 'name' },
{ data: 'height' },
{ data: 'hair_Color' },
{ data: 'skin_color' },
{ data: 'gender' }
]
} );
});
</script>
This are my scripts. I know that there are some threads about this same thing but i had no luck getting it to work, i checked Datatables documentation to try different ways but no luck, its not filling the table. The API returns me this:
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://swapi.co/api/planets/1/",
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/3/",
"https://swapi.co/api/films/1/",
"https://swapi.co/api/films/7/"
],
"species": [
"https://swapi.co/api/species/1/"
],
"vehicles": [
"https://swapi.co/api/vehicles/14/",
"https://swapi.co/api/vehicles/30/"
],
"starships": [
"https://swapi.co/api/starships/12/",
"https://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
}
Here its also a Fiddle: https://jsfiddle.net/dpq7v6ba/5/
Even you want to use object as your datasource, but your data still need to live inside a property which is need to be an array, like :
{
count:30,
data:[{...},{...},{...}......]
}
Since you want to make a list table on the screen, you should use the api that will return multiple result but not the single result api, in your api url, that is https://swapi.co/api/people/ .
by default, this library will read data from an property named "data"...
But you can give the "dataSrc" argument point out where the dataTables library should go to read the data from the response json string,
the response of the api is an one level JSON object, the data is an array of the value of the "results" property.
And you hava a wrong property mapping in the "columns" argument which should be "hair_color", not "hair_Color"
so the code will become :
$(document).ready(function() {
$('#example').DataTable( {
ajax: {
url: 'https://swapi.co/api/people/',
dataSrc: 'results'
},
columns: [
{ data: 'name' },
{ data: 'height' },
{ data: 'hair_color' },
{ data: 'skin_color' },
{ data: 'gender' }
]
} );
});
and then it will work.
JSFiddle example

Unable to select rows programatically in drawCallback() of DataTables

I am using the latest datatables with select extension. I am trying to select multiple rows programatically after the table is rendered. I am trying to achieve this in the drawCallback() as below:
var table = $('#example').DataTable({
"select": {
"style": 'multi'
},
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "age" },
{ "data": "start_date" },
{ "data": "salary" }
],
"rowId": "name",
"drawCallback": function( settings ) {
var api = new $.fn.dataTable.Api( settings );
api.rows(["[id='Bradley Greer']", "[id='Ashton Cox']"]).select();
}
});
But, I am getting an Uncaught TypeError: Cannot read property 'style' of undefined error.
Here is the link for live version - http://live.datatables.net/yemiqafu/2/
P.S: I have used [id='Bradley Greer'] as selector since there is a space in the id. I had to do this for live demo and this is not the reason for the error that is thrown.
SOLUTION
Option drawCallback is not a correct place to perform row selection.
Ideally, you should use initComplete option instead, but there was an issue with Select extension that was fixed 10/7/15 which prevented Select to work in initComplete. Until then you can use the workaround below for HTML sourced data or use nightly build of DataTables and Select extension.
For table with data from HTML source you can select your rows after DataTables initialization.
var table = $('#example').DataTable({
"select": {
"style": 'multi'
},
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "age" },
{ "data": "start_date" },
{ "data": "salary" }
],
"rowId": "name"
});
table.rows(["[id='Bradley Greer']", "[id='Ashton Cox']"]).select();
DEMO
See this example for code and demonstration of a workaround for table with HTML sourced data.
See this example for code and demonstration of using nightly JS/CSS builds for table with Ajax sourced data. This example could be used for HTML sourced data as well.

Issue loading JSON Object into Datatable Jquery

I am using DataTables with Jquery, I have an JSON object data source I want to fetch via Ajax and display in the table.
JSON data is returned from the /live/log url and is formatted as follows :
{
"Logs": [
{
"date": "2015-04-22T14:00:39.086Z",
"eventType": "event1",
"str": "Application startup"
},
{
"date": "2015-04-22T14:01:27.839Z",
"eventType": "event2",
"str": "test Logged in"
}
]
}
My Table HTML :
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Event</th>
<th>Description</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Date</th>
<th>Event</th>
<th>Description</th>
</tr>
</tfoot>
</table>
And finally the JS to fetch and populate the datatable :
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "/live/log",
"columns": [
{"data": "date"},
{"data": "eventType"},
{"data": "str"}
]
});
});
I can see via the debugger the JSON data is being fetched correctly.
I seem to get an error in the datatables js relating to the JSON data.
Value aData in fnInitalise is null - Uncaught TypeError: Cannot read property 'length' of undefined. The Datatable gets stuck saying "Loading..."
I'm sure it's probably due to my JSON data formatting. Can anyone point me in the right direction?
You should access the Log object in data, because it is the array that the column will loop through when constructing your table. The plugin works by assuming that the name of your array is called data, i.e.:
{
"data": [
// Array of objects
]
}
But since you are using Log in your case:
{
"Logs": [
// Array of objects
]
}
...you will need to manually specify the dataSrc attribute (because you are using a custom data property):
$(document).ready(function() {
$('#example').dataTable( {
"ajax": {
"url": "/live/log",
"dataSrc": "Logs"
},
"columns": [
{"data": "date"},
{"data": "eventType"},
{"data": "str"}
]
});
});

DataTables - Uncaught TypeError: Cannot read property 'length' of undefined

I've seen several examples of this problem but still haven't been able to find a resolution.
The error says it breaks on jquery.dataTables.js (version 1.10.4) on line 3287 shown below
// Got the data - add it to the table
for ( i=0 ; i<aData.length ; i++ ) {
_fnAddData( settings, aData[i] );
}
This is my controller. The controller is this way because the the lack of db connection right now, but will have JSON returned in the same format as $data. I have tried several things to resolve the error, but keep running into other issues. The JSON IS valid.
public function test()
{
$data = '{"persons": [{"branch": "CORP","phone_numbers": [{"desk": "5223422117"},{"mobile": "5022319224"},{"branch": "422-922-2291"}],"email": "twilliams#test.com","preferred_name": "Thomas","person_id": 368,"department": "IT","first_name": "Thomas","title": "Programming Manager","last_name": "Williams"}]}';
$data = json_encode($data);
echo $data;
}
My javascript
$(document).ready(function() {
$('#directory_table').dataTable( {
"ajax": {
"url": "test",
"type": "JSON"
},
"aoColumns": [
{ "persons": "preferred_name" },
{ "persons": "last_name" },
{ "persons": "phone_numbers.0" },
{ "persons": "phone_numbers.1" },
{ "persons": "phone_numbers.2" },
{ "persons": "email" },
{ "persons": "department" },
{ "persons": "title" }
]
} );
} );
My HTML
<table id='directory_table' class="display">
<thead>
<tr style='background: #186A9F; color: white;'>
<th>First Name </th>
<th>Last Name</th>
<th>Desk Number</th>
<th>Mobile</th>
<th>Branch</th>
<th>Email</th>
<th>Department</th>
<th>Title</th>
</tr>
<thead>
</table>
CAUSE
By default DataTables expects JSON response to have certain structure, see documentation.
Array of arrays:
{
"data": [
[ "value1", "value2" ],
...
]
}
Array of objects:
{
"data": [
{
"attr1": "value1",
"attr2": "value2"
},
...
]
}
Error occurs because name of the data property in your response holding array of objects (persons) differs from default (data).
SOLUTION
Use ajax.dataSrc option to define the property from the data source object (i.e. that returned by the Ajax request) to read.
$('#directory_table').dataTable( {
"ajax": {
"url": "test",
"dataSrc": "persons"
},
"columns": [
{ "data": "preferred_name" },
{ "data": "last_name" },
{ "data": "phone_numbers.0.desk" },
{ "data": "phone_numbers.1.mobile" },
{ "data": "phone_numbers.2.branch" },
{ "data": "email" },
{ "data": "department" },
{ "data": "title" }
]
});
Alternatively if you can change data property name in JSON response from persons to data, then adding "dataSrc": "persons" wouldn't be needed.
DEMO
See this jsFiddle for code and demonstration.
LINKS
See jQuery DataTables: Common JavaScript console errors for more information on this and other common console errors.

Categories

Resources