loading data from json in sencha - json

I am creating an application where i have created a list and populated the data in the list using a data store.
data.js
Ext.regModel('Contact', {
fields: ['firstName', 'lastName', 'DOB', 'group']
});
iPolis.ListStore = new Ext.data.Store({
model: 'Contact',
sorters: 'lastName',
getGroupString : function(record) {
return record.get('group');
},
data: [
{ firstName: "Domino", lastName: "Derval" , DOB: "28May2008", group:"Personalize"},
]
});
This part of the code runs fine where i get the data and display it. Now what i require is a connection to the database and retriving the data in the data.js using a json file.
Any suggestions on how thats possible?
iPolis.ListStore = new Ext.data.Store({
model : 'Contact',
proxy : {
type : 'ajax',
url : 'js/person_list.json',
reader : {
type : 'json',
//root : 'results',
// totalCount : 'total'
}
},
autoLoad : true
});
used this for getting the data but it gives me an error sayin XMLHttprequest cannot load data in file.json

Go through the Ext.data.Proxy in Sencha API and also check the examples of store in API docs.

Just replace the url property of reader to the php file.
return proper JSON

Related

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.

Loading two different json with same store

Is there a way to load different json files on demand(click), somehow changing the URL. Same store, same model, just changing the url and load().
Ext.define('app.gridStore', {
extend: 'Ext.data.Model',
fields: [
'name', 'email', 'phone'
]
});
var myStore =Ext.create('Ext.data.Store', {
model: 'app.gridStore',
proxy: {
type: 'ajax',
url : 'app/kontaktGrid.json',
reader:{
type:'json',
root: 'items'
}
}
});
buttons: [{
text: 'Load1',
handler:function(){
myStore.load().url('app/kontaktGrid1.json');
}
},{
text: 'Load2',
handler:function(){
myStore.load('app/kontaktGrid2.json');--
returning POST 405 Method not allowed
}
}]
both myStore.load().url('app/kontaktGrid1.json'); or myStore.load('app/kontaktGrid2.json'); do not update the store URL for retriving data.
In order update the url, you need to do the following:
myStore.getProxy().url = "/new-url";
myStore.load();
The first statement modifies the store's proxy url. The load() which is then called, loads the new data to the store.

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'
}
}
})
});