enter image description here
How can I get json response data from a route into js?
Okay, from what I can understand is, you want to fetch some data(JSON) from ajax and show it in your charts.
Well, it's quite easy. You must have a data variable that basically contains labels and dataset list. Just fetch the JSON and put the corresponding data values in their respective place. Then run the window.myChart.update() function. This will update the chart with the new values.
var data = { //The Default data
labels: ['2001','2002','2003','2004','2005'],
datasets: [{label: 'prices', borderWidth: 2, hoverBorderWidth: 2, backgroundColor: "rgba(0,128,128,0.5)", data: [10,30,10,50,20], borderColor: "rgba(0,128,128,1)",}] };
var ctx1 = document.getElementById('canvas3').getContext('2d');
window.myChart = new Chart(ctx1, {
type: 'radar', data: data,
options: {responsive: true, scales:{yAxes:[{ticks:{beginAtZero:true}}],xAxes: [{gridLines: {color: "rgba(0,0,0,0)",}}]}, legend: {position: 'top'}, title: {display: true,text: 'Charts'}}
});
//Now change the data list in the data.datasets[0] to the data of JSON file.
window.myChart.update()
Related
I have what I think is a very simple issue, but I just don't get how to do this data manipulation. This sadly didn't help, even though it's the same pain I am feeling with Ember.
Here is a route:
route/dashboard.js:
import Ember from 'ember';
export default Ember.Route.extend({
// this is for testing, normally we get the data from the store
model: function() {
return this.get('modelTestData');
},
modelTestData: [{
name: 'gear',
colorByPoint: true,
data: [
{y: 10, name: 'Test1'},
{y: 12, name: 'Test2'},
{y: 40, name: 'Test3'}
]
}],
});
The structure of the 'modelTestData' object has to be exactly like that as it is passed into a child component that needs it structured that way.
I can easily get my data from the API and put it into the model:
model: function() {
return this.store.get('category');
},
But then I need to restructure it...but how?
I have to somehow iterate over the categories collection and extract parts of data from each record to replace the 'data' part of the modelTestData object.
So I have 3 issues I am completely stumped on:
How to 'get at' the attributes I need from the model?
How to structure them as an array of objects with 'y' and 'name'?
How to assign that structure to the 'data' property of modelTestData instead of it being hardcoded?
Categories is a JSONAPI object like this:
{
"data":[
{
"id":"1",
"type":"categories",
"attributes":{
"name":"Carrying system",
"total-grams":"0.0"
}
},
{
"id":"2",
"type":"categories",
"attributes":{
"name":"Shelter system",
"total-grams":"0.0"
}
}
]
}
I need to map the grams value to 'y' and the name to 'name' in modelTestData.
Note that the category data is used in other routes for other purposes exactly as returned by the API. So I don't want to change the model structure itself, or what the API returns...that will break other parts of the app that do use 'category' in its original structure.
This is a specific use case that this route needs to massage the data to pass to the child component as per the structure of modelTestData.
I also wonder whether this data manipulation task belongs in a route?
Should I somehow do this in the serliazer adapter, creating a new structure as say 'categoryWeights' so I can then do:
model: function() {
return this.store.get('categoryWeights');
},
EDIT
I have managed to do this in the route, but it just gives me an array of objects. I need a single object containing 2 properties and an embedded array of objects.
model() {
return this.store.findAll('category')
.then(categories => categories.map(category => {
let data = {
y: category.get('totalGrams'),
name: category.get('name')
};
return data;
}))
},
This should probably go into a computed property:
dataForSubModel: Ember.computed('model.#each.totalGrams', 'model.#each.name', {
get() {
return [{name: 'gear', colorByPoint: true, this.get('model').map(m => ({y:m.get('totalGrams'), name:m.get('name')}))}
}
}),
The serializer is the wrong place, because its not that you need to convert it between the server and your app, but between your app and a strange component.
Actually the best thing would be to refactor the component.
Ok I got this to work in the route.
model() {
return this.store.findAll('category')
.then( function(categories) {
let data = [];
data = categories.map(category => {
return {
y: category.get('totalGrams'),
name: category.get('name')
}
});
return [{name: 'gear', colorByPoint: true, data}];
})
},
I still have the feeling this should be done in the adapter or serializer. Would be happy to see answers that show how to do that.
I have a grid that I am creating drawing off a JSON data source that is formatted like this:
[{"user":{"username":"foo","url":"bar"}},
[{"product":{"name":"banana","price":"85"}},
{"product":{"name":"peach","price":"66"}},
{"product":{"name":"strawberry","price":"78"}}
]
]
But I cannot figure out how to tell datagrid to use the contents of the products to populate the datagrid. Here is my datagrid code:
<script>
require(["dojo/store/JsonRest"], function (JsonRest) {
myStore = new JsonRest({ target: 'myurl', handleAs: 'json'
});
});
require(["dojox/grid/DataGrid", "dojo/data/ObjectStore", "dojo/domReady!"
], function (DataGrid, ObjectStore) {
grid = new DataGrid({
store: dataStore = new ObjectStore({ objectStore: myStore }),
structure: [
{ name: "Procuct", field: "name", width: "200px" }
]
}, "grid3");
grid.startup();
});
</script>
<div id="grid3"></div>
I do not get any error, but I cannot see that the grid gets populated.
It is a similar question to THIS, but the data structure is a bit different.
I think it has something to do with your json structure.
The first part of your jsonArray is an object, the second an array:
[object,ArrayOfProducts]
How should DataGrid find the necessary data if you hide it in an array within an array & then inside the attribute product.
Try passing something simple via json like:
[{"name":"banana","price":"85"},
{"name":"peach","price":"66"},
{"name":"strawberry","price":"78"}]
Have you tried grid.renderArray(dataStore) to populate the grid with the conent ?
An option is to append a new property to the json object prior to dataStore.query() call. This can be accomplished with dojo/aspect. See article for other examples.
aspect.before(dataStore, "query", function(items) {
items.forEach(function(item) {
//Do something here. I'll combine two properties.
item.newProperty = item.propertyValueA + "-" item.propertyValueB;
return item;
});
return items;
});
When dataStore.query() is called, the function above is called above. This results in a new property be added to the json object. In the example above, the newProperty is a concatenation of propertyValueA and propertyValueB.
This may allow you to manipulate the json as needed.
I try to display some data in my Sencha touch application, but it doesn't work... and i can't find what I'm doing wrong.
My webSiste return a json object who look like this
[{"name":"a","id":1}]
the script is getting the Json and display it:
Ext.regApplication({ name: 'Command',
phoneStartupScreen: 'phone-startup.png',
phoneIcon: 'apple-touch-icon.png',
launch: function(){
this.viewport = new Ext.Panel(
{
layout: 'fit',
fullscreen: true,
items: [{xtype: 'list',
itemTpl: new Ext.XTemplate('<div>{name}</div>'),
store: stores
}],
dockedItems: [{xtype: "toolbar",
dock: "top",
title: 'MovieCommand',
items: [{ui: 'back',text: 'back',handler: function(){}}]
}]
});
}
});
Ext.regModel('Commands', {
fields: ['name', 'id' ]
});
var stores = new Ext.data.Store(
{model: 'Commands',
proxy: {type: 'scripttag',
url: 'http://localhost:8080/GTI710/commandes/liste.htm',
format: 'sencha',
reader: new Ext.data.JsonReader ({
type: 'json',
})
},
});
stores.load();
I don't have any error in the java script but nothing is displayed.
I just want to have the "a" displayed but it doesn't work, I don't know why...
The ScriptTagProxy, which you are using, requires a response from server that's composed of legitimate Javascript code.
Specifically, the code is a callback function with the desired JSON data you what as the its first argument:
someCallback([{"name":"a","id":1}]);
The name of someCallback is generated dynamically by Sencha Touch when the request is sent. In other words, your attempt to store the response with a static file will not work.
The name of someCallback is passed as a parameter in the GET request sent by Sencha Touch, the key of which defaults to callback.
If you don't want to have a web server as the data source, checkout Ext.util.JSONP.
Is there anyway to remotely override/replace a GridPanel's store?
I have a grid that has a dummy store as I get an error if I don't declare as store:
this.ds is undefined
When my form is submitted, it makes a GET REST call & loads a JSON store with the results. I want this store to be the store of my grid and show it underneath the formPanel.
I can get it to show & return JSON but can't seem to replace the store.
I tried using
searchGrid.store = formStore //the JSONStore returned from form submit
EDIT
This if the data store:
var formStore = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '...',
method: 'GET'
}),
root: 'Report',
fields:[
....]
});
This is the loading / changing of the store:
var data = this.getForm().getValues();
formStore.load({
params: {
fields: Ext.encode(data)
}
});
var grid = Ext.getCmp('search');
Ext.apply(grid, {store: formStore});
grid.show();
Try this
myGridPanel.getStore().proxy.setApi({read: url});
myGridPanel.getStore().load();
I'm using this solution when I want to read data from another url
grid.reconfigure(store, colModel);
Works fine for me. Is the formStore.data compatible with Grid's columns configuration? You don't need to specify the column model in the reconfigure call if it didn't change.
Show a slice of your formStore.data and grid configuration.
Have you tried Ext.apply()?
From the api:
apply( Object object, Object config, Object defaults ) : Object
EDIT:
Here's how you use it:
Ext.apply(myGrid, { store : mystore }); //no need for the third parameter, but if you do want a default, then you can use one
Should the root is inside reader? Like this
var formStore = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '...',
method: 'GET'
}),
reader: {
type: 'json',
root: 'Report'
},
fields:[
....]
});
I managed to solve this by moving the jsonStore to the grid itself and make it a singleton. Then reference to it from the form using StoreMgr
I am new to dojo and spring development. I am trying to populate a Tree widget using a json response from a spring-mvc controller. I'm following the examples from the dojocampus website quite closely.
Firstly if I use a local data source it works ok:
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
dojo.addOnLoad(function() {
var rawdata = [{"rid":"b1c","name":"Test Parent","children":[{"rid":"1c4","name":"Test Child 1","children":[]},{"rid":"ee6","name":"Test Child 2","children":[]}]}];
var store = new dojo.data.ItemFileReadStore({
data: {
identifier: 'rid',
label: 'name',
items: rawdata
}
});
var treeModel = new dijit.tree.TreeStoreModel({
store: store,
query: {name: 'Test Parent'},
childrenAttrs: ["children"]
});
new dijit.Tree({
model: treeModel
},
"treeOne");
});
</script>
<div id="treeOne">
</div>
But if I use my json url the tree doesn't appear:
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
dojo.addOnLoad(function() {
var store = new dojo.data.ItemFileReadStore({
url: "/Demo2/glossaryobjects/categories.json"
});
var treeModel = new dijit.tree.TreeStoreModel({
store: store,
query: {name: 'Test Parent'},
childrenAttrs: ["children"]
});
new dijit.Tree({
model: treeModel
},
"treeOne");
});
</script>
<div id="treeOne">
</div>
When I debug with Firebug I can see that the json response appears to be loaded correctly. It looks like this:
{"identifier":"rid","items":{"rid":"b1c","name":"Test Parent",
"children":[{"rid":"1c4","name":"Test Child 1","children":[]},
{"rid":"ee6","name":"Test Child 2","children":[]}]}, "label":"name"}
There is an error in Firebug:
"dijit.tree.TreeStoreModel: query {"name":"Test Parent"} returned 0 items, but must return exactly one item"
It looks like the ItemFileReadStore is not correctly loaded. Anyone know what I'm doing wrong? I've been tearing my hair out for days trying to get this to work, so any help is much appreciated.
Cheers,
Rod.
OK! Problem solved (for me):
If you have a close look at the store produced by each, the data is there for both, but the way the store represents each is different.
With the url JSON data, you get
_arrayofallitems []
_arrayoftoplevelitems Object {....
id...
items...
etc.
with the string data, you get
_arrayofallitems [] 62 items
_arrayoftoplevelitems
[0]
id
items
etc.
If you intercept the JSON response from xhrGet, and compare it to the string, you'll see that the JSON response is not an array (no []) whereas the string is.
Solution: declare an empty array, push the JSON response into it,
then pass the array to ItemFileReadStore:
dojo.xhrGet( {
url: 'test.php',
handleAs: "json",
preventCache: 'true',
load: function(response, ioArgs){
var rawdata = [];
rawdata.push(response);
var store = new dojo.data.ItemFileReadStore({ data: {
identifier: "id",
label: "label",
items: rawdata }
});
loadtree(store);
}});
It worked for me (finished an afternoon of frustration)...
The error you mentioned:
"dijit.tree.TreeStoreModel: query {"name":"Test Parent"} returned 0 items, but must return exactly one item"
Should be from using a TreeStoreModel instead of a ForestStoreModel. The former requires only one item be returned for the root node. Your fix probably worked because you shoved it into a single array.
Take a look at:
http://ofps.oreilly.com/titles/9780596516482/application_widgets.html