How can i load data from a json file - json

i use extjs and load a json file with the store loader.
I want to load a json file. It will contain "totalRecords" and i want to put this in a var. For example var Records. This way i can display it at some positions of my app and use it for alerts.
thanks to your help i know have this:
total = Ext.create('Ext.data.Store', {
model: 'step1',
proxy: {
type: 'ajax',
url: 'testevents.json',
reader: {
type: 'json',
root: 'slaevents'
}
},
listeners: {
load: function() {
records = total.getRange()
test = records[0].get('event')
alert('1 =' +test)
}
},
autoLoad:true
});
alert('2 =' +test)
This will show alert with "1 =other". That is correct. And "2 =undifined". That is wrong. How can i use the test outside of this store?
Thanks

Realize that your store doesn't load instantly so it has nothing in it when you assign it to a variable immediately afterwards in the js. You need to listen for the store to load and then assign it, or assign it in a callback. For example, this works fine:
// get the countries
var countries = Ext.create('Ext.data.Store', {
fields: ['id','name'],
proxy: {
type: 'ajax',
url: '../getCountries',
reader: 'json'
},
listeners: {
load: function() {
records = countries.getRange()
alert(records[0].get('name'))
}
}
});
This alerts "Argentina".
records becomes an array of Ext.data.Model objects each of which have all the methods that Ext.data.Model has. This is covered here in the API.

Related

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' }
]

Not able to perform CURD operations properly in my Extjs app using Json-Server

I am using Json-server to test CURD operations in my extjs grid. I have put some dummy data on json-server and I am able to read, delete, update and edit that data.
But When I create data using my extjs app, I am not able to delete or edit that data cause auto generated Id is "nameOfMyModel + autoIncrementNumber".
My Store is:
Ext.define('ThemeApp.store.peopleStore', {
extend: 'Ext.data.Store',
model: 'ThemeApp.model.peopleModel',
storeId: 'peopleStore',
pageSize: 500,
autoLoad: true,
autoSync: true
});
Model is:
Ext.define('ThemeApp.model.peopleModel', {
extend: 'Ext.data.Model',
fields: [ 'id' ,'title','body'],
proxy: {
type: 'rest',
//format: 'json',
limitParam:"",
filterParam: "",
startParam:'',
pageParam:'',
url:'http://localhost:3000/posts',
api: {
read : 'http://localhost:3000/db',
create: 'http://localhost:3000/posts',
update : 'http://localhost:3000/posts' ,
destroy : 'http://localhost:3000/posts'
},
headers: {'Content-Type': "application/json" },
reader: {
type: 'json',
rootProperty:'posts'
},
writer: {
type: 'json'
}
}
});
And I am Adding user like:
var UserStore = Ext.getStore('peopleStore');
var user = Ext.create('ThemeApp.model.peopleModel',{title: "Test", body: "Testing" });
user.save(); //POST /users
UserStore.load();
And For Deletion:
var grid = button.up('gridpanel');
var selection = grid.getView().getSelectionModel().getSelection()[0];
if (selection) {
UserStore.remove(selection);
UserStore.load();
}
Can anyone tell me why I am not able to delete/update records which I generate via extjs app?
The Id of simple post is like
http://localhost:3000/posts/(number like 1 or 2)
and of app generated record is
http://localhost:3000/posts/ThemeApp.model.peopleModel-1
And I can see app generated record in database.json but browser is saying that this url doesn"t exist.
Kindly point out my mistake
Reason you can't delete them is because they are not created properly. First of all to generate sequential ids use
identifier: 'sequential' in your model, than it will generate numeric id's
You can read it in detail here Model identifier
After doing this generate new objects and see if you can handle them properly.

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.

Accessing nested objects in JSON feed - Sencha Touch

I'll begin with the usual disclaimer: new to Sencha Touch/working with JSON, floundering in the dark. Any help or prodding in the right direction is appreciated more than you know!
I'm trying to get my app to fetch data from a public Google Spreadsheet JSON feed. From what I've managed to figure out, my current model is based on JSON arrays, NOT nested objects. How do I access and return a nested object?
Ext.regModel('Count', {
fields: [{name:'$t'}]
});
this.list = new Ext.List({
itemTpl: new Ext.XTemplate('<div>{$t}</div>'),
loadingText: false,
store: new Ext.data.Store({
model: 'Count',
proxy: {
type: 'scripttag',
url : 'http://spreadsheets.google.com/feeds/cells/0AuYDRk91MX8-dHhkV29ZVkRGNjlvZjV4QVBIVmJubVE/odb/public/basic?range=A1&alt=json',
reader: {
type: 'json',
root: 'feed'
}
}
})
});
The JSON data (extra stuff removed, above link will show all of it if need be, contains an email address I'd rather not post and have indexed):
{
"feed":{
"entry":[{
"content":{
"type":"text",
"$t":"11"
}
}]
}
}
If I plop in another JSON feed that uses arrays I can work with it just fine, but just can't figure out what I need to do to access that integer in the object that corresponds to $t. If I put "entry" as the root instead of "feed," I get an error that reads, "Uncaught TypeError: Cannot read property 'length' of undefined."
The solution! Turns out Sencha didn't like the $ in my template variable.
Ext.regModel('Count', {
fields: [{name:'count', mapping:'content.$t'}]
});
this.list = new Ext.List({
itemTpl: new Ext.XTemplate('<div>{count}</div>'),
loadingText: false,
store: new Ext.data.Store({
model: 'Count',
proxy: {
type: 'scripttag',
url : 'http://spreadsheets.google.com/feeds/cells/0AuYDRk91MX8-dHhkV29ZVkRGNjlvZjV4QVBIVmJubVE/odb/public/basic?range=A1&alt=json',
reader: {
type: 'json',
root: 'feed.entry'
}
}
})
});