JSON array Tabulator js table - javascript

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.

Related

Using an array of subelements on a HTML datatable

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>

mongoose index already exists with different options

I am implementing search result view to my app.
I figured out that mongoose internally provide full text search function with $text.
I put the code below to Post.js
PostSchema.index({desc: 'text'}); //for example
Here's the code I put in my routing file route/posts.js
Post.find({$text: {$search : 'please work!'}}).exec(function (err, posts) {...})
The error message I come up with is below
Index with pattern: { _fts: "text", _ftsx: 1 } already exists with different options
Would there any body who know how to deal with this error and figure out?
Thanks you.
check on which field you have your text index defined. Right now mongodb allows only one text index per collection. so if you have defined a text index on desc column and try to use that index on some other column you are bound to get this error.
can you try to query your index and see on which column you created it. To get indexes you can do
db.collection.getIndexes()
and it will return something like this
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "some.ns"
},
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "desc_text",
"ns" : "some.ns",
"weights" : {
"title" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 2
}
]
now if you want to scope in other columns also to use this index simply drop this index
db.collection.dropIndex('desc_text');
and then recreate it by including all columns you want to be covered by text index,
db.collection.createIndex({
title:'text;,
body: 'text;,
desc: 'text',
...... and so on
});

Send additional data to KendoUI DataSource and use it in dataBound event

I want to get some additional data in the dataSource to use it in the dataBound event.
Here is transport I use in the grid:
"transport" : {
"read" : {
"url" : "f?p=120:0:701647109622339:PLUGIN=BC",
"dataType" : "json",
},
},
"pageSize" : 20,
"schema" : {
data : "row",
total : "total",
rowsdata : "rowsdata",
model : {
"id" : "doc_id",
}
},
I want to access rowsdata via $('#grid').data("kendoGrid").dataSource.data().rowsdata. Is it possible?
Here is a jsfiddle: http://jsfiddle.net/M8jvz/10/
In this particular case, I want to pass a list of permanently hidden columns into HideGrouped function
Here is the fiddle with the solution http://jsfiddle.net/Casufi/4ya83/2/
$('#grid').data("kendoGrid").dataSource.data()
Returns array. And what is that rowsdata inside your schema? Such configuration is not supported.
How to send addtional arguments to the server is covered here.
You can use dataSource.schema.data as an function to achieve what you want:
var dataSource = new kendo.data.DataSource({
"autoSync" : true,
"data" : l_json,
"pageSize" : 20,
"schema" : {
data : function(data){
data.rowsdata[0] = { hidden: 0, name: "name" }
return data.row;
},
...
Documentation here:
http://docs.kendoui.com/api/framework/datasource#configuration-schema.data

Fetch the specific column value from Datatable when user clicks

I have a datatable populated with aaData which is depicting the task created by users. Now, there is an action column in datatable which has two or three action buttons or logos like pdf - to view the user guide of that task, browse- link for the source code of the task and one is contributors logo which onclick should display the contributors for that particular task.
The aaData is of the following format which is populating the table
"aaData": [
[
"JSAG Home Page",
"JSAG Home page contains information about various POCs done",
"05/12/2012",
[
{
"displayValue":"Browse",
"link":"http://myTask.com/home",
"displayIcon" : "browselogo"
},
{
"displayValue":"Source Code",
"link":"svn/HomePage/trunk/",
"displayIcon" : "svnlogo"
},
{
"displayValue":"Audience Overview",
"link":"svn/Documents/Audience Overview.pdf",
"displayIcon" : "pdflogo"
},
{
"displayValue":"Contributors: ABC,XYZ",
"link":"#",
"displayIcon" : "people"
}
],
],
[
"Backlog",
"Backlog Forum application is designed to provide a platform for different groups to maintain backlog task items. ",
"25/08/2012",
[
{
"displayValue":"Browse",
"link":"http://mytask.com/BacklogApp",
"displayIcon" : "browselogo"
},
{
"displayValue":"Source Code",
"link":"svn/trunk/webapp-project/",
"displayIcon" : "svnlogo"
},
{
"displayValue":"Contributors: ABC",
"link":"#",
"displayIcon" : "people"
}
],
]
]
This format is for all datatables and contributors logo is there in all. What i wanted was, when user clicks the contributors icon, he should be able to see those contributors "ABC, XYZ, PQR".
I thought of fetching the action column data and then $each() the contributors array but i am not able to proceed with it.
How can i achieve this thing? How can i pick up the column value onclick because each datatable is being populated dynamically.
Please help.
Below is the code to populate a contributors div
$(document).on('click', '#contributor', function(contributors){
$.each(contributors, function(i, data) {
var ul_data = "<li><h3>"+ data+ "</h3></li>";
$("#contributors_div").append(ul_data);
});
}
$('#contributors_div').show();
});
How do i getrecentActdata as my contributors JSON array
Its going to be similar to this, provided you are declaring you datatable in the variable oTable
$(document).on('click', '#contributor', function(){
var aPos = oTable.fnGetPosition( $(this) );
console.log(aPos);
//if aPos returns an array in console, use first val at pos zero to get row data
var aData = oTable.fnGetData(aPos[0]);
console.log(aData);
// inspect your returned object, then tailor your $.each iteration
$.each( aData["contributors"], function(i, data) {
var ul_data = "<li><h3>"+ data+ "</h3></li>";
$("#contributors_div").append(ul_data);
});
}
$('#contributors_div').show();
});

ExtJS: return total rows/records in json store

I have a json store that returns values in json format. Now I need to get the number of rows/records in the json string but when I use store.getCount() function it returns 0, but the combobox is populated with rows, and when I use store.length I get undefined, probably because its not an array anymore, its returning from store, which is calling php script. Anyways, whats the best approach for this problem?
Try this out:
var myStore = Ext.extend(Ext.data.JsonStore, {
... config...,
count : 0,
listeners : {
load : function(){
this.count = this.getCount();
}
}
Ext.reg('myStore', myStore);
and then use inside panels:
items : [{
xtype : 'myStore',
id : 'myStoreId'
}]
Whenever you need to get the count then you can simply do this:
Ext.getCmp('myStoreId').count
Your Json response from server, can be something like this...
{
"total": 9999,
"success": true,
"users": [
{
"id": 1,
"name": "Foo",
"email": "foo#bar.com"
}
]
}
Then you can use reader: {
type : 'json',
root : 'users',
totalProperty : 'total',
successProperty: 'success'
} in your store object.
As from docs if your data source provided you can call getTotalCount to get dataset size.
If you use ajax proxy for the store, smth like
proxy : {
type : 'ajax',
url : 'YOUR URL',
reader : {
type : 'json',
root : 'NAME OF YOUR ROOT ELEMENT',
totalProperty : 'NAME OF YOUR TOTAL PROPERTY' // requiered for paging
}
}
and then load your store like
store.load();
There will be sent Ajax asynchronous request, so you should check count in callback like this
store.load({
callback : function(records, operation, success) {
console.log(this.getCount()); // count considering paging
console.log(this.getTotalCount()); // total size
// or even
console.log(records.length); // number of returned records = getCount()
}
});

Categories