I have some JSON data looking like this:
{"data":[{"one":"[[1756.53, 2.419583], [13755.95, 0.056274], [1755.62, 0.027065], [11755.59, 0.085065], [1175.28, 906], [11752.33, 0.333531], [11752.31, 0.5], [11752.03, 0.6], [11752.02, 0.107656], [1751.99, 1.288268], ....
This json is being retrieved through a AJAX request and served to a HTML datatable:
$(document).ready(function() {
var table = $('#mytable').DataTable({
"serverSide": true,
"ajax": "/api/?format=datatables",
"columns": [
{
data: 'one',
}
]
});
setInterval( function () {
table.ajax.reload();
}, 10000 );
});
Where api is the api endpoint.
The problem with my actual code is that, when loading the HTML datatable, i will see the data being rendered like this
DATA:
[[1848, 84857], [4944, 4949], [34, 65], [3566, 78], .... ]
Basically all the JSON gets thrown in a single row of the table.
Instead, i would like to have each record in a single line, like:
DATA
1848, 84857
4944 4949
....
After investigating in the network response, i've come to the conclusion that my code sees the JSON response as a string, and not as an array with sub-elements (an array with a series of arrays, each one with two items), hence datatables cannot iterate over it.
Is there any way to fix this issue?
Actually your main problem is JSON response format. Object data should contains array of object or array of array. But now seems it was "json string" in object "one".
If you can't override your json response from server side, we can altering/relocating data source using Datatables AJAX DataSrc option.
Option of dataSrc is to provide the ability to alter what data DataTables
will read from the JSON returned from the server, or to manipulate the
data from one form into another (be it JSON to another form of JSON,
XML, YAML etc).
We need to two (2) part to solve your problem:
Relocate JSON data using DataSrc option
Convert JSON string as object using using JSON.parse
code:
var table = $('#mytable').DataTable({
"ajax": {
"type" : "GET",
"url" : "/endpoint/?format=datatables",
"dataSrc": function ( json ) {
console.log(JSON.parse(json.data[0].one));
return JSON.parse(json.data[0].one);
}
},
"columns": [
{"data":0, "title":"col1"},
{"data":1, "title":"col2"}
]
});
Working demo:
//This is for JSON request/response mocking only. Do not use this when you have a live JSON server
$.mockjax({
url: "/endpoint/?format=datatables",
response: function(settings) {
this.responseText = {
"draw": settings.data.draw,
"recordsTotal": 4,
"recordsFiltered": 4,
"data": [
{"one":"[[1756.53, 2.419583], [13755.95, 0.056274], [1755.62, 0.027065], [11755.59, 0.085065], [1175.28, 906], [11752.33, 0.333531], [11752.31, 0.5], [11752.03, 0.6], [11752.02, 0.107656], [1751.99, 1.288268]]"}
]
}
}
});
$(document).ready(function() {
var table = $('#mytable').DataTable({
"ajax": {
"type" : "GET",
"url" : "/endpoint/?format=datatables",
"dataSrc": function ( json ) {
console.log(JSON.parse(json.data[0].one));
return JSON.parse(json.data[0].one);
}
},
"columns": [
{"data":0, "title":"col1"},
{"data":1, "title":"col2"}
]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="mytable" class="display nowrap" width="100%"></table>
Related
now i got some error when i try to get data and display on the datatables which using serverSide.
following to my code below i have get my data by using ajax POST method because i want to send some data that need to use to filter in my database, and this is my code.
Javascript
report_table = $('#report_table').DataTable({
"scrollX": true,
"serverSide":true,
"deferRender": true,
"ajax": {
"url": "load_report_table",
"type": "POST",
"data":{
'region_id': function() { return $('#select_reg').val() },
}
},
});
Python
from datatables import ColumnDT, DataTables
from flask import request
#app.route('/load_report_table', methods=['POST', 'GET'])
def load_report_table():
reg_id = request.form['region_id']
columns = [
ColumnDT(Battery_Log.time),
ColumnDT(Battery.serial_number),
ColumnDT(Battery_Log.usage),
]
query = db.session.query().select_from(Battery, Battery_Log)\
.filter(Battery.reg_id == reg_id, Battery_Log.battery_id == Battery.id)
params = request.args.to_dict()
rowTable = DataTables(params, query, columns)
return rowTable.output_result()
but when i print rowTable.output_result() it got the error like this.
{'draw': '1', 'recordsTotal': '14733', 'recordsFiltered': '14733', 'error': "int() argument must be a string, a bytes-like object or a number, not 'NoneType'"}
For now i guess the error that cause by using POST method because when i have change my code to call only url and not post any data to the route function it work normally, the code is show below.
report_table = $('#report_table').DataTable({
"scrollX": true,
"serverSide":true,
"deferRender": true,
"ajax": "load_report_table"
});
So are there anyway to fix that i can POST my data to my route function and return the data to show on the datatables.
Hi I have the following data but cannot get DataTables to display it:
const data = [{
"School":"Arsenal 2011",
"Group":{
"Name":"Previous",
"ParentGroup":{
"Name":"Arsenal",
"ParentGroup":{
"Name":"USA",
"ParentGroup":null
}
}
},
"GroupDisplayText":null,
"Publisher":"Abbot",
"PublishedDate":"2011",
"PublishersWebsite":"http://google.com/USA/ADW%202011/Arsenal%202011.pdf"
},
{
"School":"New York 2000",
"Group":{
"Name":"New York",
"ParentGroup":{
"Name":"USA",
"ParentGroup":null
}
},
"GroupDisplayText":null,
"Publisher":"DoE",
"PublishedDate":"2000",
"PublishersWebsite":"http://google.com/USA/New York%202000%20Tables.pdf"
}];
$(document).ready(function () {
$('#example').DataTable( {
"ajax": data
} );
}
I have created a project on playcode
https://playcode.io/470603
I am getting a datatables error
DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
I have checked the json and all is ok?
Thanks
$(document).ready(function () {
$('#example').DataTable( {
data:data // ajax for to make ajax request to retrieve data.
"columns": [ // also needs to specify column config to display it
{ "data": "School" },
]
} );
}
for javascript object use data instead.
I am trying to populate datatable on click.
Initially I have this configuration:
var json = [];
var shippingMethodsTable = $("#shipping-methods-table").DataTable({
'data': json,
"columns": [
{ "data": "ShippingMethodId" },
{ "data": "MethodName"},
{ "data": "Code"},
{ "data": "ShippingTypeName" },
{ "data": "MaxWeight" }
]
});
After I click button I have json object of arrays:
json = ko.toJSON(data.shippingMethods); // I am using knockout.js to populate it
Result:
"[{"ShippingMethodId":2,"MethodName":"Priority Mail","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"},{"ShippingMethodId":4,"MethodName":"Priority Mail Express","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"},{"ShippingMethodId":5,"MethodName":"First-Class Mail","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"13 oz"},{"ShippingMethodId":6,"MethodName":"USPS Retail Ground","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"},{"ShippingMethodId":8,"MethodName":"Media Mail","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"}]"
And then I am trying to update datatable
shippingMethodsTable.clear();
shippingMethodsTable.rows.add('{"data":' + json + '}');
shippingMethodsTable.draw();
But getting an error: Requested unknown parameter 'ShippingMethodId' for row 0, column 0
Method rows.add() expects array of object, rather than object.
So, try
shippingMethodsTable.clear();
shippingMethodsTable.rows.add(json);
shippingMethodsTable.draw();
instead.
I am trying to display a tree structure in my web project.
I am using Symfony 3.4.x with jsTree v3.3.5.
PROBLEM
I can not get the tree to display when using json and ajax.
I am using an example from official jstree documentation.
If i hard code data in json format the tree is displayed without a hitch, but when i return the same json as part of ajax call - tree is not displayed (i get only one item, displayed as a folder, without a name).
I want to display all the tree nodes fully open - so loading all items is required.
CODE
my data in json format (i am using alternative json notation as per jstree documentation)
{"success":true,
"data":[
{"id":"50","parent":"#","text":"test_root"},
{"id":"51","parent":"50","text":"test_1"},
{"id":"123","parent":"51","text":"test_2"},
{"id":"73","parent":"51","text":"test_3"},
{"id":"75","parent":"51","text":"test_4"},
{"id":"76","parent":"51","text":"test_5"},
{"id":"74","parent":"51","text":"test_6"},
{"id":"78","parent":"51","text":"test_7"},
{"id":"124","parent":"51","text":"test_8"},
{"id":"77","parent":"50","text":"test_9"}
]}
using jstree
$(document).ready(function()
{
let project_tree;
project_tree = $('#file-tree-json');
project_tree.jstree({
'core':
{
'data':
{
'url': '/tree/prepare',
'dataType': 'json',
'data': function (node) {
console.log(node);
return { 'id': node.id };
},
}
},
"types": {
"root": {
"icon": "lnr lnr-home"
},
"folder": {
"icon": "lnr lnr-folder"
},
"file": {
"icon": "lnr lnr-file-empty"
}
},
"search": {
show_only_matches: true,
search_callback: function (str, node)
{
if (node.text.toLowerCase().indexOf(str) >= 0) { return true; }
}
},
"plugins": [ "types", "search" ]
});
}
code in my controller that prepares tree items data in json format
$em = $this->getDoctrine()->getManager();
$repo_file_tree = $em->getRepository('App:FileTree');
try
{
$build_my_tree_json = $repo_file_tree->prepareJsonTree($build_my_tree);
return new JsonResponse([
'success' => true,
'data' => $build_my_tree_json
]);
}
catch (\Exception $exception)
{
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
Other discussions on SO that are related and which i already read, but in my opinion, they did not solve the problem at hand or/and refer to jstree version that is out of date
jsTree unable to load root nodes from AJAX call
jsTree - loading subnodes via ajax on demand
JSTree - Load nodes dynamically
JStree and ajax
https://stackoverflow.com/a/22965656
CONCLUSION
What am i doing wrong?
Maybe i am overlooking some detail or technicality?
Thank you for your comments and answers.
UPDATE 1
when i am returning only data
return new JsonResponse([
$build_my_tree_json
]);
i get additional "[]" as so
[[
{"id":"50","parent":"#","text":"test_root"},
{"id":"51","parent":"50","text":"test_1"},
{"id":"123","parent":"51","text":"test_2"},
{"id":"73","parent":"51","text":"test_3"},
{"id":"75","parent":"51","text":"test_4"},
{"id":"76","parent":"51","text":"test_5"},
{"id":"74","parent":"51","text":"test_6"},
{"id":"78","parent":"51","text":"test_7"},
{"id":"124","parent":"51","text":"test_8"},
{"id":"77","parent":"50","text":"test_9"}
]]
How can one remove extra "[]" from json or reference inner array?
UPDATE 2
it works when there are returned only data about tree nodes in json format.
working example
return new JsonResponse($build_my_tree_json);
So how to make jstree work with additional data in ajax response?
There should be a way to extract all the data about tree from response that contains status and data (response as displayed in my questions CODE section).
The structure of your JSON response doesn't work well with jsTree. jsTree expects an Array of nodes. Your output structure has an array inside the data object. You should have a structure as below in your response for it to work.
[
{
"id": "50",
"parent": "#",
"text": "test_root",
"opened":true
},
{
"id": "51",
"parent": "50",
"text": "test_1"
},
{
"id": "123",
"parent": "51",
"text": "test_2"
},
...
...
]
I have a Tabulator datatable in my HTML file. Looks like this:
<div class="example-table">/div>
I have a JavaScript file that would populate my table with data by calling a rest API that returns with a JSON.
This is how my JS file looks like:
$(document).ready(function() {
$(".example-table").tabulator({
columns : [ {
title : "ID",
field : "myjson.firstname",
width : 250
}, {
title : "Pred",
field : "myjson.pred",
sorter : "number",
align : "left",
formatter : "progress",
width : 200
}, ],
});
var tabledata = [];
$.getJSON('http://127.0.0.1:7001/MySerices/service/rest', function(json) {
tabledata.append(json);
});
$(".example-table").tabulator("setData", tabledata);
});
And the JSON which the REST service returns with looks like this:
{"myjson":
[{"firstname":"Piter","pred":"0,616540492"},
{"firstname":"Piter","pred":"0,616540492"}
]}
The Tabulator table apears but without any data. If I check my JS log, I can see the request is done wihout any error, and i can see the JSON in my response.
Can you help me how can I do it?
Thank you!
There are three major errors in your code.
First, your JSON response, the response should be as the tabulator js documentation shows:
//An array of objects not wrapped in an object
[
{"firstname":"Piter","pred":"0,616540492"},
{"firstname":"Parker","pred":"0,42325456"}
]
Second, the columns field should match each row:
$(".example-table").tabulator({
columns : [ {
title : "ID",
field : "firstname",//changed here
width : 250
}, {
title : "Pred",
field : "pred",//and here
sorter : "number",
align : "left",
formatter : "progress",
width : 200
}, ],
});
Third, getJSON is asynchronous, so you need to get and set the data only when the response arrives:
$.getJSON('http://127.0.0.1:7001/MySerices/service/rest', function(response) {
//response is already a parsed JSON
$(".example-table").tabulator("setData", response);
});
PS: arrays don't have the append method, you can use unshift or pushto prepend or append data to the array.