Ext JS: Load single database entry into model - ajax

I'm trying to create a model with a single database entry, instead of creating a store for just one row... doesn't make sense. Anyway, I can create the model by using the static load method, but the URL for my model's proxy is dynamic, so that's not an option, as I want to just load on the fly. Also, creating an instance of the model doesn't seem to work because I can't use the load method, due to it being static...
I've started experimenting with an Ajax call to grab the data, and then loading it into an instance of the model, but the association relationships seem to not get created, even though the plain field values do. This is what I'm attempting to do:
Code
// SectionsModel
Ext.define('SectionsModel', {
extend: 'Ext.data.Model',
fields: ['name']
});
// MY_MODEL
Ext.define('MY_MODEL', {
extend: 'Ext.data.Model',
fields: ['name', 'id'],
hasMany: [{
associationKey: 'sections', name: 'getSections', model: 'SectionsModel'
}],
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'configuration'
}
}
});
var url = 'my/url';
Ext.Ajax.request({
url: url,
method: 'GET',
scope: this,
success: function(res) {
var configObj = Ext.decode(res.responseText);
var configModel = Ext.create('MY_MODEL', configObj);
console.log(configModel);
},
failure: function(res) {
console.error('failed');
}
});
Response
{
"code": 200,
"configuration": {
"name": "TestConfiguration",
"id": 1,
"sections": [{
"name": "section1"
}, {
"name": "section2"
}]
}
}
The above code is dummy code that I wrote for this example... think of it as pseudocode if it doesn't work. Like I said, it does work when I use the static load method, and I can successfully make the Ajax call... the issue is how to create a model with the given data. Would I need to pass in config to the model's constructor, and set the model's proxy's data to the passed in config? Is that proper protocol? I'm just trying to figure out the best approach here. Thanks!
Cross-posted from the Sencha forums.

I have come up with a solution, thanks to one of Mitchell Simoens' blog post. I changed MY_MODEL to look like this:
Ext.define('MY_MODEL', {
extend: 'Ext.data.Model',
fields: ['name', 'id'],
hasMany: [{
associationKey: 'sections', name: 'getSections', model: 'SectionsModel'
}],
constructor: function(data) {
this.callParent([data]);
var proxy = this.getProxy();
if (proxy) {
var reader = proxy.getReader();
if (reader) {
// this function is crucial... otherwise, the associations are not populated
reader.readAssociated(this, data);
}
}
},
proxy: {
type: 'memory',
reader: {
type: 'json'
}
}
});
// in the success of the Ajax call
success: function(res) {
var configObj = Ext.decode(res.responseText);
var configModel = Ext.create('MY_MODEL', configObj.configuration);
console.log(configModel);
}

Related

Kendo DropDownList Not Binding Data

I am using a Kendo dropdownlist to display data made from a remote service call.
First, here is the definition in the HTML template:
<select
kendo-drop-down-list
k-options="dropdownOptions"
k-ng-delay="dropdownOptions">
</select>
Next, here is the code to populate the dropdown from an AngularJS controller:
var myUrl = '(url of REST service)';
$scope.dropdownOptions = {
dataSource: {
transport: {
read: {
url: myUrl,
dataType: 'json',
type: 'POST',
contentType: "application/json;charset=ISO-8859-1"
},
parameterMap: function (data, type) {
const req = {
"PARAMS": $scope.params
};
return JSON.stringify(req);
}
}
},
dataTextField: 'DESCRIPTION',
dataValueField: 'VALUE',
schema: {
type: "json",
data: "resultData",
model: {
id: "VALUE",
fields: {
"VALUE":{field: "VALUE", type: "string"},
"DESCRIPTION":{field: "DESCRIPTION", type: "string"}
}
}
}
};
(Note: the REST service requires data to be provided as a JSON object via POST, hence the type and parameterMap).
I have confirmed that the data to populate the dropdown is being returned from the REST service as an array under the key "resultData":
{
"resultData":[{"DESCRIPTION":"Whatever","VALUE":"VALUE1"},...]
}
Can anyone help me?
Update
I am also seeing "e.slice is not a function" in my dev console.
Edit
Added id field to model, no effect.
The problem was that schema should have been a child of dataSource. Once I fixed that, the data began to display.

retrieve data for grid/chart from httpwebrequest call to url

I am trying to get a grid filled with the json response I would receive when making a httpwebrequest call to a url endpoint which requires authentication. The data will be in json form:
{
"data": [
{
"value": "(\"Samsung Health\")",
"tag": "ME"
},
{
"value": "(\"Samsung Galaxy Tab\")",
"tag": "HIM"
},
{
"value": "(\"Amazon fire\")",
"tag": "ME"
}
]
}
I am not sure how to even start and whether to use Ext.Ajax.Request or some type of call from code behind. I am using vb.net in code behind. Any suggestions appreciated. Sample code for ajax call;
function getMembers() {
var parameters = {
node: dynamicNodeId
}
Ext.Ajax.Request({
url: 'https://data.json',
method: 'GET',
jsonData: Ext.encode(parameters),
success: function (response, opts) {
alert('I WORKED!');
//decode json string
var responseData = Ext.decode(response.responseText);
//Load store from here
memberStore.loadData(responseData);
},
failure: function (response, opts) {
alert('I DID NOT WORK!');
}
});
}
The grid formation:
var grid = Ext.create('Ext.grid.Panel', {
store: store,
stateful: true,
stateId: 'stateGrid',
columns: [
{
text: 'Query',
flex: 1,
sortable: false,
dataIndex: 'query'
},
{
text: 'Last Updated',
width: 85,
sortable: true,
renderer: Ext.util.Format.dateRenderer('m/d/Y'),
dataIndex: 'lastChange'
},
Here query would be the value from the json response and lastChange the current datetime. I tried the proxy request call and realized that since I am calling an endpoint on a different domain I needed to use jsonp.
var myStore = Ext.create('Ext.data.Store', {
model: 'User',
proxy: {
type: 'jsonp',
extraParams: {
login: 'username',
password: 'password'
},
url: 'https://api.data/rules.json',
reader: {
type: 'json',
root: 'rules'
},
callbackParam: 'callback'
},
autoLoad: true
});
I might have to just figure out some other way to do by making sure all the data I needed is called to a database by some other function.
The best approach for your situation would be to create store that is configured with a remote proxy. See the example at the top of this documentation page: http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.Store
The remote proxy will take care of the AJAX request to retrieve the data, and the store will automatically manage casting the data results to Ext.data.Model instances. Once the store is loaded with data, the grid to which the store is bound will also automatically handle rendering the data that has been populated into the store.

How to load json data from ajax in ExtJs

I try to get started with ExtJs, and I have quite basic question.
I have a model
Ext.define('Mb.model.User', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'int' },
{ name: 'name', type: 'string' },
...
],
proxy: {
type: 'ajax',
url : 'server/gui/getUser.php'
}
});
getUser.php returns a json string (it is the logged in user, and not a user out of a user table):
{"id":"1","name": ... }
I tried the following to load the data, but I get an error Uncaught TypeError: Object [object Object] has no method 'load'
Ext.define('Mb.Application', {
...
launch: function() {
....
user = Ext.create('Mb.model.User');
user.load();
}
});
What is the correct way to load that data ?
An additional question: What is the benefit of using Modelhere ?
Couldn't I do something like this ?
Ext.Ajax.request({
url: 'server/gui/getUser.php',
success: function(response){
var user = Ext.JSON.decode(response.responseText);
}
});
In this case load is a static method. You can load a model from your server by passing the id.
Mb.model.User.load(id, {
success: function(rec) {
console.log('loaded', rec.getData());
}
});
The advantage to using a model is the layer of abstraction, + the extra functionality you get from using a model.
You can do, but with little changes
myRequest = Ext.Ajax.request({
url: 'getdata.php',
method: 'GET',
callback: function(response) {
console.log(response.responseText);
}
});

ExtJS store.loadData() doesn't load the JSON data

I am trying to load a JSON data which is replied back by an AJAX request to a grid.
My store definition:
Ext.define('Report.store.CustomerDataStore', {
extend: 'Ext.data.Store',
requires: [
'Report.model.Customer'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
storeId: 'CustomerDataStore',
model: 'Report.model.Customer',
proxy: {
type: 'ajax',
url: '',
reader: {
type: 'json',
root: 'data',
record: 'fields'
}
}
}, cfg)]);
}
});
There is a button in my app which is defined as follows:
xtype: 'button',
handler: function(button, event) {
var queryform = this.up('form').getForm();
var me = this;
if(queryform.isValid())
{
Ext.Ajax.request({
url: 'customers/', // where you wanna post
success: function(response) {
var mystore = Ext.data.StoreManager.lookup('CustomerDataStore');
var myData = Ext.JSON.decode(response.responseText);
console.log(myData.toSource());
mystore.loadData(myData);
},
jsonData: Ext.JSON.encode(queryform.getValues())
});
}
},
The problem is that my grid doesn't show the replied data! I am sure that my replied JSON format is OK. I have checked it with a json file. also myData.toSource() returns my desired JSON format.
I am pretty confused what I am doing wrong?
Could you plz help?
I found the solution, I had to use loadRawData() function instead of loadData().
loadData() loads models i.e. records, and doesn't parse JSON data inside. You need to specify your JSON format in proxy reader and then store will automatically do Ajax call when you call store.load()

How to retrieve data from a jsp page to my store using Sencha Touch 2

I would like an example of this. Please give me a detailed example.
If you want to store the results in a Store, first create your model like this:
Ext.define('app.model.Example', {
extend: 'Ext.data.Model',
config: {
fields: ['data'],
}
});
Next, create your Store:
Ext.define('app.store.Examples', {
extend: 'Ext.data.Store',
config: {
model: 'app.model.Example',
autoLoad: true,
autoSync: true,
},
});
An example of JSONP request is easy to find in Sencha Touch 2 Kitchensink Demo. Here I added some code to add the results to your store:
Ext.data.JsonP.request({
url: 'http://free.worldweatheronline.com/feed/weather.ashx',
callbackKey: 'callback',
params: {
key: '23f6a0ab24185952101705',
q: '94301', // Palo Alto
format: 'json',
num_of_days: 5
},
callback: function(success, result) {
var store = Ext.getStore('Examples');
var weather = result.data.weather;
if (weather) {
store.add({data: weather});
}
else {
alert('There was an error retrieving the weather.');
}
panel.getParent().unmask();
}
});
Hope it helps ... Let me know if there are any errors.

Resources