Extjs 3.4 populate grid after ajax call - json

Using Extjs 3.4
My web service respond with a json string: {"msg":"Some"}
I want to populate a grid with Some .
Ext.onReady(function(){
var store = new Ext.data.JsonStore({
url: "my/json/url.json",
fields: [{name:"msg"}]
});
function StoreLoadCallback(records, operation, success){
if (success) {
console.log(records); // record is undefined
alert(records); // show 'undefined'
} else {
console.log('error');
}
}
function ajaxSearch_function(){
var query = Ext.getCmp('search').getValue();
store.load({
params: {query: query},
callback: StoreLoadCallback
});
}
var form = new Ext.FormPanel({
defaultType: 'textfield',
items: [{
fieldLabel: 'search',
name: 'search',
id: 'search'
}],
buttons: [{
text: 'Search', handler: ajaxSearch_function
}]
});
form.render('ajax-search_form');
var grid = new Ext.grid.GridPanel({
store: store,
columns: [{
id :'title',
header : 'title',
sortable : true,
dataIndex: 'title'
}],
});
grid.render('ajax-grid');
});
The web service respond well, I have tested with Curl.
The problem is populate the grid with the json response.

If you say that records variable in callback method is undefined, there is probably a problem with parsing the response. I guess it expects array instead of one single record. Try to change the contents of the json file from {"msg" : "Some"} to [{"msg" : "Some"}]
After you cross this hurdle (i. e. the response is correctly parsed), I see that your datagrid column refer to "title" rather than "msg". Title is not a member of the store, so the columns will show empty value anyway.
Also, it is not common to start method name with capital letters (except they represent "classes"), so it is kind of nicer to call the method storeLoadCallback instead of StoreLoadCallback.

Related

EXTJS How to use JSon Reader without proxy

Below is the code where I try to load some records using JSon Reader in the store.
I am unable to see this on the Grid.
Can you please point me out what am I missing as I don't want to use proxy/url for JSon.
var itemsPerPage = 10;
Ext.Loader.setConfig({enabled: true});
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.toolbar.Paging'
]);
Ext.define('Assemble', {
extend: 'Ext.data.Model',
fields: [
{name: 'lot_no', type: "string"}
],
idProperty: 'lot_no'
});
Ext.onReady(function() {
Ext.QuickTips.init();
var jsonString = '{"result":[{"lot_no":"MT6261"},{"lot_no":"MT6262"},{"lot_no":"MT6263"}]}';
// create the data store
var store = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
proxy:{
type: 'ajax',
reader: {
type: 'json',
root: 'result',
model: Assemble
}
}
});
store.loadData(Ext.decode(jsonString));
console.log(store);
var pagingToolbar = Ext.create('Ext.PagingToolbar',{
pageSize: itemsPerPage,
store: store,
displayInfo: true,
displayMsg: ' {0}-{1},{2}',
emptyMsg: "empty."
});
// create the Grid
var grid = Ext.create('Ext.grid.Panel', {
store: store,
disableSelection: true,
loadMask: true,
columns: [
{
text : 'LOT_NO',
flex : 1,
sortable : true,
dataIndex: 'lot_no'
}
],
bbar : pagingToolbar,
renderTo: 'grid',
viewConfig: {
stripeRows: true,
enableTextSelection: true
}
});
store.loadPage(1);
});
Proxy has to use with url. So, you can't use the proxy like that. I removed the proxy, put the model in store and you have to load objects into store, but in your case contained rootProperty('result', I only get the main objects or you can remove the 'result' from the jsonString). Then, it worked. Chck this fiddle:
https://fiddle.sencha.com/#fiddle/11or
var jsonString = '{"result":[{"lot_no":"MT6261"},{"lot_no":"MT6262"},{"lot_no":"MT6263"}]}';
// create the data store
var store = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
model: 'Assemble'
});
store.loadData(Ext.decode(jsonString).result);
Why are you even using a reader? Your data is local so just decode the string and pass in what you want:
https://fiddle.sencha.com/#fiddle/11qc
Also, your data is local so no need for a paging toolbar. In Ext JS 5+ the grid will use the buffered renderer (if the grid has a defined size from height/width configs or from a parent layout) so loading all the data into the store will not affect performance (other than creating the records). The grid will only render what is viewable plus a few on either side.

extjs error on filling store

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

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.

loading data from json in sencha

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

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