unable to store json data in grid store in extjs - javascript

I want to display data in grid using extjs. Data from servlet is in json format.
and below is my code...problem is that i am unable to capture output from servlet to extjs.
I want to display data in grid using extjs. Data from servlet is in json format.
and below is my code...problem is that i am unable to capture output from servlet to extjs.
Ext.onReady(function(){
var myData = null;
Ext.Ajax.request({
url : 'AccessServlet',
method : 'GET',
success: function (result, request) {
myData = Ext.decode(result.responseText);
store.loadData(myData);
},
failure: function ( result, request) {
Ext.MessageBox.alert('Failed', result.responseText);
}
});
var store = new Ext.data.ArrayStore({
fields: [
{name: 'name' },
{name: 'salary'},
{name: 'sno' },
]
});
var grid = new Ext.grid.GridPanel({
store : store,
height : 350,
width : 400
columns: [
{
header: 'SNO',
width : 100
},
{
header: 'NAME',
width : 100
},
{
header: 'SALARY',
width : 100
},
],
});
grid.render('example-grid');
});

Do not use Ajax to load store, use proxy config and appropriate reader.
Is your data array of arrays? Maybe your json has wrong format

Related

JSON array Tabulator js table

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.

C3 js, how to access json data received in url call

Below is the code to generate barchart using C3 js library
var chart = c3.generate({
bindto: '#barchart',
data: {
url: './API/get_bar_chart_data.php',
mimeType: 'json',
type: 'bar',
keys: {
x: 'category', // it's possible to specify 'x' when category axis
value: [ 'number']
},
onclick: function (d, i) {
console.log(chart.categories()[d.index]);
onclick_barchart();
}
},
bar: {
width: {
ratio: 0.5 // this makes bar width 50% of length between ticks
}
},
axis: {
x: {
type: 'category' // this needed to load string x value
}
}
});
In the above code I am getting data from URL in json format.
Now on click I want to pass this complete json received to onclick_barchart() function.
C3.js converts data received in internal format, so there's no way to get data as received.
IMO, there're 2 ways to handle this.
If you need to handle data keeping as received, maybe you need to call separately. Not in context of C3.js.
// call api and assign the result in separate variable
var data = call_ajax("./API/get_bar_chart_data.php");
var chart = c3.generate({
data: {
columns: data
onclick: function() {
onclick_barchart(data);
}
},
...
}
Or, access transformed data via internal data variable
In this case, you need to handle the format as your necessity.
var chart = c3.generate({
data: {
columns: data
onclick: function() {
// You can access in outside via 'chart.internal.data.targets'
// They're same result from .data() API
// https://naver.github.io/billboard.js/release/latest/doc/Chart.html#data
onclick_barchart(this.data.targets);
}
},
...
}

JSON Result for Flot Chart Data Format

I try generates bar chart using flot chart, I got a problem.
I have Json response like this below :
[{"label":"Total Sales",
"color":"#4345D1",
"data":"[['09-21-2016',3],['09-19-2016',1],['09-13-2016',2],
['10-21-2016',2]]"
}]
but chart never shown, I guess "data" value may contains double quotes ("),
how to convert them, that can be used in correct format, like this :
[{"label":"Total Sales",
"color":"#4345D1",
"data": [['09-21-2016',3],['09-19-2016',1],['09-13-2016',2],
['10-21-2016',2]]
}]
Additional Coding :
Here are mysql query data source
select 'Total Sales' as label,
concat('[',group_concat("[",concat('\"',trxdate,'\"',",",qty),"]"),']')
as data
from(
select
DATE_FORMAT(trxdate,'%m-%d-%Y') as trxdate,
sum(quantity) as qty from Journals
group by
DATE_FORMAT(trxdate,'%m-%d-%Y')
) as A;
So I put them into nodejs as REST API,
and then here are service adapter :
$http({
method: 'GET',
url: vm.barsrc
}).then(
function successCallback(response) {
var datArr = response.data[0];
var datachart = ( datArr.data ).replace('"','').replace('"','');
var result = [
{
label: datArr.label,
color: datArr.color,
data: datachart
}
];
vm.StackedBarDataset = result;
}, function errorCallback(response) {
...
}
);
Thank you in advanced.
#derek :

Why does this datagrid sort in a weird order?

I have a datagrid where each row has a column where I have defined a formatter to format the display result depending on what it says in the database and create a div with a background color depending on the database.
I have this structure for my datagrid:
structure: [
{
name: "Name",
field: "name",
width: "auto"
},
{
name: "Initials",
field: "initials"
},
{
name: "E-mail",
field: "email",
width: "auto"
},
{
name: "Kerberos",
field: "kerberos",
width: "120px",
formatter: function(kerberos){
var format = "";
if(kerberos == "password expired" || kerberos == "account expired"){
format = '<div class="yellow" title="'+kerberos+'">'+kerberos+'</div>';
}else if(kerberos == "ok"){
format = '<div class="green" title="'+kerberos+'">'+kerberos+'</div>';
}else{
format = '<div class="red" title="Has no kerberos account">not available</div>';
}
return format;
}
},
When I press the column header to sort, it sorts the rows, put not consistent, so I don't know if it sorts correctly (see image below). How do I define the way the datagrid have to sort this column?
I was thinking it was the HTML <div...> part I do in the formatter due to the <> characters, but it still sorts weird if I only output the text (which by my understanding, should be sorted alphabetically). Does anyone know why this happens and how I can fix it?
EDIT:
forgot to add how i get/assign data. I get a lot of data from a xhr.post in JSON format, then i do as follows:
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
handleAs: "json",
content: {
psearch: "dojoXhrBlank"
},
load: function(jsondata){
// Creating a store for the datagrid
var personStore = new Memory({ data: jsondata });
// Create datastore for datagrid
var gridStore = ObjectStore({objectStore: personStore});
...
I found an answer. The problem lies in ObjectStore. This store (for some reason) wont sort properly and after changing the store type to ItemFileReadStore it sortet properly. The other reason for switching store was that ItemFileReadStore also supports the comparatorMap attribute which allows for custom sorting, ObjectStore dose not support this attribute.
solution:
load: function(jsondata){
var store = new ItemFileReadStore({
data: { identifier: "id", items: jsondata }
});
pgrid = new DataGrid({
store: store,
...

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