Issue loading JSON Object into Datatable Jquery - javascript

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"}
]
});
});

Related

How to the get primary key in API using a javascripts

Im using Django classbased views CRUD but my frontend is DataTables API RestFramework, My problem is how can I get the Primary Key per rows to Edit and Delete the Data? I can display all the data in DataTables but I can't edit and delete since primary key is not found.
Thank You.
JS
<script>
$(document).ready(function() {
var table = $('#table').DataTable({
"ajax": "/api/mlist/?format=datatables",
"columns": [
{
"data": "A_Id",
"render": function(data, type, row, meta){
if(type === 'display'){
data = '' + data + '';
}
return data;
}
},
});
</script>
Table.html
<table id="table" class="table table-striped table-bordered" style="width:100%" data-server-side="true" data-ajax="/api/mlist/?format=datatables">
<thead>
<tr>
<th>Act No</th>
</tr>
</thead>
</table>
API list
GET /api/mlist/
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"count": 3,
"next": null,
"previous": null,
"results": [
{
"id": 2377,
"A_Id": "VML2020-000000",
}
]
}

Datatables.net json data load

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" }
]
});

Bootstrap dataTable search and pagination is not working when data is loading from ajax API response

I developing a admin panel. I am able to load data that is getting from Ajax API response in bootstrap dataTable but default search and pagination of the table is not working.
I tried
"processing": true,
"serverSide": true
to initialize the table but it is not working.
Is It possible this dataTable functionality work as default provided by the Bootstrap dataTable.
I want to achieve the following steps:
Step1: A form with submit button.
Step2: When clicked on submit, make an ajax call and get JSON Data back to add it into dataTable rows dynamically.
Step3:
$("#editable-sample").DataTable({ // what should I do here.});
Problem
Data is loading but search box and pagination is not woking on the page.
Can you post your code?
Are you sure you fulfilled the dataTables prerequisites:
The table must have <thead> and <tbody> tags
The table must have an id that is used in the launch script example:
<table class="table table-bordered" id="dataTables-example">
<script>
$(document).ready(function() {
$('#dataTables-example').dataTable();
});
</script>
datatables supports Ajax data source (objects), see
Below you can see an example which taken from dataTables' doc
JS
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "data/objects.txt", //
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
AJAX
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
}
]
}
$.ajax({..
success: function(data) {..
var table = $('#datatable').DataTable();
table.clear().draw();
var rowNode= new Array();
for (var key=0, size=data.length; key<size; key++){
var j = -1;
var r = new Array();
// represent columns as array
r[++j] ='<tr><td><input type="hidden" name="somename1" value="'+data[key].id+'"/><input type="hidden" name="somename2" value="'+data[key].is_deleted+'"/>'+data[key].lic_category_name+'</td>';
r[++j] = '<td>'+data[key].someval1+'</td>';
r[++j] = '<td>'+ data[key].someval2+'</td>';
r[++j] = '<td>'+ data[key].someval13+ '</td>';
r[++j] ='<td class="last"><i class="fa fa-eye"></i> <i class="fa fa-edit"></i> <i class="fa fa-trash"></i></td></tr>';
rowNode = table.row.add(r);
}
rowNode.draw().node()
}
}
My JSON Response,
[{"id":70,"somekey1":"GC 1","somekey2":"GC 1","somekey3":8,"somekey4":5000,"somekey5":1,"somekey5":1,"is_deleted":0}]
It worked for me ..
The problem occurred because of 'column' attribute try to match data row values with column before it get the data.
so i place the close Curly bracket of 'ajax' attribute before 'column' attribute.
now the column attribute function get call only after ajax function is complete.
$(document).ready(function() {
$('#example').DataTable( {
"ajax":{ "data/objects.txt" },//<------------------------------------------------place here//
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
});
} );

Efficient way to Populate Table with multidimensional JSON

I'm looking to the most efficient way to convert this json.
{
"Kitchen":{
"protocol":[
"pollin"
],
"id":[
{
"systemcode":31,
"unitcode":1
}
],
"state":"off"
},
"BBQ":{
"protocol":[
"pollin"
],
"id":[
{
"systemcode":31,
"unitcode":4
}
],
"state":"off"
},
"Server":{
"protocol":[
"pollin"
],
"id":[
{
"systemcode":15,
"unitcode":1
}
],
"state":"off"
}
}
Into the following table:
[Name] [Protocol] [Systemcode] [S] [State]
Kitchen pollin 31 1 off
BBQ pollin 31 4 off
Server pollin 15 1 off
My page consists of a table in html and jquery is already loaded.
<table class="table" id="tableDevices">
<thead>
<tr>
<th>Name</th>
<th>Protocol</th>
<th>Systemcode</th>
<th>Unitcode</th>
<th>State</th>
</tr>
</thead>
</table>
Now I'm looking for the fastest way to loop trough the JSON, and populate the table with the data. I first flattened the JSON, and then fed it to the table with a loop. However the code I modified to flatten the JSON was painfully slow. This is the my first time working with version control and javascript and I apparently didn't commit my code properly. I'm looking for the most efficient way to fill this table and I'm stuck myself so can someone show my the most efficient way to do this?
I'm going to assume you've parsed the JSON and have a variable, data, that refers to the parsed result.
Then it's a simple for-in loop:
var tbody = $("<tbody>");
var key, entry, tr;
for (key in data) {
entry = data[key];
tr = $("<tr>");
$("<td>").text(key).appendTo(tr);
$("<td>").text(entry.protocol[0]).appendTo(tr);
$("<td>").text(entry.id[0].systemcode).appendTo(tr);
$("<td>").text(entry.id[0].unitcode).appendTo(tr);
$("<td>").text(entry.state).appendTo(tr);
tr.appendTo(tbody);
}
tbody.appendTo("#tableDevices");
That said, you might look at a templating library like Handlebars instead.
Live Example:
// This stands in for the parsed JSON
var data = {
"Kitchen": {
"protocol": [
"pollin"
],
"id": [{
"systemcode": 31,
"unitcode": 1
}],
"state": "off"
},
"BBQ": {
"protocol": [
"pollin"
],
"id": [{
"systemcode": 31,
"unitcode": 4
}],
"state": "off"
},
"Server": {
"protocol": [
"pollin"
],
"id": [{
"systemcode": 15,
"unitcode": 1
}],
"state": "off"
}
};
var tbody = $("<tbody>");
var key, entry, tr;
for (key in data) {
entry = data[key];
tr = $("<tr>");
$("<td>").text(key).appendTo(tr);
$("<td>").text(entry.protocol[0]).appendTo(tr);
$("<td>").text(entry.id[0].systemcode).appendTo(tr);
$("<td>").text(entry.id[0].unitcode).appendTo(tr);
$("<td>").text(entry.state).appendTo(tr);
tr.appendTo(tbody);
}
tbody.appendTo("#tableDevices");
<table class="table" id="tableDevices">
<thead>
<tr>
<th>Name</th>
<th>Protocol</th>
<th>Systemcode</th>
<th>Unitcode</th>
<th>State</th>
</tr>
</thead>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Note that the JSON structure is fairly odd. You have arrays lying around that have just one entry in them.
Why not use Datables instead? You will have most of the burden of populating the table lifted from your shoulders.

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