extjs error on filling store - json

I have a java map. I converted it to json string and I obtain something like this :
{"NEW ZEALAND":"111111111111111","CHAD":"1","MOROCCO":"111","LATVIA":"11"}
Now I want to use it in a store and then a chart like the following code but it's not working. I have no error just no display.
var obj = Ext.Ajax.request({
url: App.rootPath + '/controller/home/dashboard/test.json',
method:'GET',
success: function(response) {
return Ext.JSON.decode(response.responseText);
}
});
var store2 = Ext.create('Ext.data.Store', {
model: 'PopulationPoint',
data: obj
});
Ext.create('Ext.chart.Chart', {
renderTo: 'infos2',
width: 500,
height: 300,
store: store2,
series: [
{
type: 'pie',
field: 'population',
label: {
field: 'state',
display: 'rotate',
font: '12px Arial'
}
}
]
});

The AJAX request is asynchronous. As such, the obj variable used to initialize your data won't contain your data yet.
One option is to create the store2 variable and create the chart directly in the success callback of the AJAX request.
A cleaner option would be to configure the store with a proxy to load the url, and in the callback create the chart.
EDIT
The JSON response does not contain the fields that are declared in your model (sent in the comments). Update the JSON to return a properly formatted model and the chart should work as seen in this fiddle. The JSON should look something like
[
{
"state" : "New Zealand",
"population" : 111111111
},
{
"state" : "Chad",
"population" : 1
}
]

Related

Alfresco webscript: AJAX, JSON

I've successfully created a webscript to that returns a JSON response. See below:
get.js file:
// search for folder within Alfresco content repository
var folder = roothome.childByNamePath("PATH");
// validate that folder has been found
if (folder == undefined || !folder.isContainer) {
status.code = 404;
status.message = "Folder " + " not found.";
status.redirect = true;
}
// construct model for response template to render
model.folder = folder;
get.json.ftl:
{"corporates" : [
<#recurse_macro node=folder depth=0/>
]
}
<#macro recurse_macro node depth>
<#list node.children?sort_by(["properties","name"]) as child>
{
"Name" : "${child.properties.name}",
"URL" : "${child.url}",
"serviceURL" : "${child.serviceUrl}",
"shareURL" : "${child.shareUrl}",
"ID" : "${child.id}",
"Type" : "${child.typeShort}"
},
<#if child.isContainer>
{
<#recurse_macro node=child depth=depth+1/>
}
</#if>
</#list>
</#macro>
This returns JSON cleanly (woohoo!), but I would like to grab the JSON from a second webscript using AJAX.
Currently, I am utilizing a typical AJAX call in my second webscript's get.html.ftl file like this:
$(document).ready(function() {
$('.submit-button').click(function(e) {
// Avoid to trigger the default action of the event.
e.preventDefault();
// Actions declared here...
$.ajax({
type: 'GET',
dataType: 'html',
url: 'PLACEHOLDER_URL_PATH',
success: function(data) {
// Shows the result into the result panel.
$('#alfresco-result').html(data);
alert('Done.');
},
error: function(data) {
// Shows the result into the result panel.
$('#alfresco-result').html("ERROR");
}
});
});
})
My question is why the AJAX call doesn't work when I use dataType: 'json'?
I would like to parse through the JSON in my AJAX call and turn it into html (e.g. an html list), but it's not accepting the JSON dataType as an acceptable input.
Any help is appreciated!
You can use POST Webscript Call using ajax like this and pass your jsonObject
dataObj:"yourJsonObject",
to dataObject
Alfresco.util.Ajax.jsonPost(
{
url: Alfresco.constants.PROXY_URI + "sample/mypostwebscript",
dataObj:"yourJsonObject",
successCallback: {
fn: function(res){
alert("success");
alert(res.responseText);
},
scope: this
},
failureCallback:
{
fn: function(response)
{
// Display error message and reload
Alfresco.util.PopupManager.displayPrompt(
{
title: Alfresco.util.message("message.failure", this.name),
text: "search failed"
});
},
scope: this
}
});
},

Complicated nested json loops to store with extjs

I'm using a geojson extracted from naturalearthdata which looks like that :
All I want is to catch the NAME of each feature in order to display them in a grid (live search grid.. BTW is it efficient for 2000 names?)
But I can't access to all the name with root property. I tried to loop into all the features
Ext.define('myApp.store.Places', {
extend: 'Ext.data.Store',
alias: 'store.places',
requires : ['myApp.model.PlacesModel',
'myApp.view.main.MainModel'],
id: 'Places',
model: 'myApp.model.PlacesModel',
autoLoad: true,
proxy: {
type: 'ajax',
url : '/resources/data/coord.json',
reader: {
type: 'json',
transform: {
fn: function(data) {
for(var i = 0; i < data.features.length -1; i++){
names_places.push(data.features[i].properties.NAME);
}
debugger;
return names_places;
},
scope: this
}
}
}
});
But the debugger sent me that result which I don't understand :
Especially when the array looks good :
What is the good way to catch only the NAME? Does the return has to look to a json?
You can use the mapping attribute on the fields array in your model definition to map the correct attribute in the json to a field.
You set the rootProperty to features for the reader.
Then in your fields array something similar to this
fields: [
{ name: 'myCustomField', mapping: 'properties.NAME' }
]

Load JSON data directly into highcharts angular

I am using https://github.com/pablojim/highcharts-ng to build Highcharts in my angularjs app. As suggested on that site I am configuring my chart configs in my controller as follows:
$scope.chartConfig6 = {
options: {
chart: {
type: 'bar'
}
},
series: [{
data: [33, 55, 10, 18, 17]
}],
title: {
text: 'Agent FNOL Ranking'
},
loading: false
}
Now I have a json file: http://pastebin.com/SEu8dHkB if you do a search you can find the field called "highChart" on the json which contains the configurations for a highchart. Now I want to be able to use these configurations directly from the json to to my highcharts config either in the controller or as a directive. This is how I get the json file via http in my service:
.factory('Swoop',function($http,$filter,$q){
return {
all: function(){
var deferred = $q.defer();
$http.get("swoop.json").success(
function(data){
// angular.copy(data, studies);
deferred.resolve(data);
}
);
return deferred.promise;
}
}})
However, I am not sure how I could render this data(under the highChart object in the json) to the $scope.chartConfig6 like I did above. Can someone please show me how this could be done?

Dojo ItemFileWriteStore not reading JSON server file

I am using Dojo and it's dojo/data/ItemFileWriteStore module to read a JSON data file on my local server. In my .js file I have
var myDataStore = new ItemFileWriteStore({
url: "app/data/mydata.json",
handleAs: "json",
clearOnClose: true,
urlPreventCache: true
})
This is located in the postCreate function for my return declare function... so:
define([
"dojo/_base/declare",
"com/cayuse/base/_widget",
"dojo/text!./templates/myform.html",
...
"dojo/data/ItemFileWriteStore",
"dojo/store/DataStore",
"dojo/store/Observable",
"dojo/data/ObjectStore",
"dojo/domReady!"
],
function(declare, widget, template, ..., ItemFileWriteStore, DataStore,
Observable, ObjectStore){
return declare("app.myform", widget, {
templateString: template,
postCreate: function(){
domConstruct.create("link",{
type: "text/css",
rel: "stylesheet",
href: require.toUrl('dojox/form/resources/CheckedMultiSelect.css')
}, document.getElementsByTagName("head")[0]);
// data store
var myDataStore = new ItemFileWriteStore({
url: "app/data/mydata.json",
handleAs: "json",
clearOnClose: true,
urlPreventCache: true
})
console.log(myDataStore);
}
});
}
);
I can change the data store access from what you see above using IFWS method to
var myDataStore = dojo.xhrGet({
url: "app/data/mydata.json",
handleAs: "json",
load: function(data, ioArgs){
console.log(data);
}
});
and it finds the file with no problems.
This is so bizarre! Any ideas on what is going wrong here?
UPDATED:
Here is the data in the file I am reading. I believe it conforms to the JSON format. Let me know if not. xhrGet reads it fine.
{ "identifier": "id",
"label": "firstName",
"items":[
{"id":"0","firstName":"Robert","website":"www.barker.com","email":"robert#barker.com","bday":"1928-08-09","color":"Blue","toolkits":["Dojo","Moo"],"sendEmail":["on"],"format":"HTML"},
{"id":"1","firstName":"Vanna","website":"www.white.com","email":"vanna#white.com","bday":"1968-07-23","color":"Green","toolkits":["Dojo","jQuery"],"sendEmail":["off"],"format":"Text"}
]
}
ItemFileWriteStore requires your data being structured into something like this:
{ identifier: 'abbr',
label: 'name',
items: [
{ abbr:'ec', name:'Ecuador', capital:'Quito' },
{ abbr:'eg', name:'Egypt', capital:'Cairo' },
{ abbr:'sv', name:'El Salvador', capital:'San Salvador' },
{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo' },
{ abbr:'er', name:'Eritrea', capital:'Asmara' },
{ abbr:'ee', name:'Estonia', capital:'Tallinn' },
{ abbr:'et', name:'Ethiopia', capital:'Addis Ababa' }
]}
That is 'identifier' being your "ID" field, 'label' being your "label" field and then all your objects inside an array called "items".
You can check it out here in ItemFileWriteStore's documentation. If you don't have your JSON data structured like that it's possible that you may end up reading your file with the IFWS and actually not reading any data.
There are other store implementations in dojo 1.7 that don't require such structure, e.g. Memory Store that you can combine with other file reading techniques to achieve the same.
Try using dojo.data.ItemFileReadStore for reading
json data files, instead of dojo/data/ItemFileWriteStore.
Note that dojo.data.ItemFileWriteStore is used for writting json data.
If your code is EXACTLY as you posted it above then the interpreter might not like the fact that you omitted the semicolon from the ItemFileWriteStore assignment. Try adding the ';' as below:
// data store
var myDataStore = new ItemFileWriteStore({
url: "app/data/mydata.json",
handleAs: "json",
clearOnClose: true,
urlPreventCache: true
});
console.log(myDataStore);

How to make a store with jsonreader using metadata in Extjs 4?

Is it possible to create a store that will read json, and use fields specified in the metadata in the json as a model?
I want to say something like:
var store = new Ext.data.Store({
autoLoad: {
params: {
metaNeeded: true
}
},
reader: new Ext.data.JsonReader({fields:[]}),
proxy: new Ext.data.HttpProxy({
api: {
url: 'php/chart-data.php'
}
})
});
I've tried a number of combinations however I cannot seem to get it to work.
I currently get the error "Cannot call method 'indexOf' of undefined". I've had others including "object has no read method".
The json I am sending is:
{
metadata:{
root:"rows",
sortInfo:{
field:"date",
direction:"ASC"
},
fields:[ {
name:"date"
}, {
name:"flow"
},{
name:"limit"
}
],
idProperty:"date"
},
success:true,
rows: << snip >>
}
Is it possible to have the store's model configured by the data that it receives, so I could use the same store later with different fields (e.g. date, flow, limit and temperature)?
I have gotten it to work with the following:
var store = new Ext.data.Store({
proxy: {
type: 'ajax',
url: 'php/chart-data2.php',
reader: new Ext.data.JsonReader({
fields:[]
})
}
});
And the php that sends the json:
'{"metaData":{
"root":"rows",
"fields": [
{"name":"date",
"type":"number",
"convert": function(val, rec) {
return val*1000
} },
{"name":"flow"},
{"name":"limit"}
]
},
"totalCount":'.count($chart).',
"success":true,
"rows":' . json_encode($chart) . '
}'
This now allows the server to specify the data (that's getting displayed in a chart), and can add in series dynamically. I don't know if it is good, but it works. I am kind of disappointed in the lack of documentation about this.