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

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()

Related

Jquery Data Tables Can't post data with Ajax (asp.Net)

I've been trying to post data to jquery Data Tables but i couldn't. I have a web method in server side which returns data as object array. I need to get data with ajax post. But i can't. So i need some help.
Here is my c# web method:
[WebMethod]
public static object[] Questions()
{
table = new DataTable();
List<object> questionList = new List<object>();
table = RunSelectCommand("SELECT QUESTION_ID,QUESTION_TEXT,QUESTION_GROUP FROM QUESTIONS WHERE QUESTION_ACTIVE='Y'");
for(int i=0 ; i<table.Rows.Count ; i++)
{
questionList.Add(new
{
q_id = table.Rows[i]["QUESTION_ID"].ToString(),
q_text = table.Rows[i]["QUESTION_TEXT"].ToString(),
q_group = table.Rows[i]["QUESTION_GROUP"].ToString()
});
}
return questionList.ToArray();
}
And jquery:
$(document).ready(function () {
$('#questTable').DataTable({
processing: true,
serverSide:true,
ajax: {
url: 'Question.aspx/Questions',
type:'POST'
},
columns: [
{ data: 'q_id' },
{ data: 'q_text' },
{ data: 'q_group' }
]
});
});
But i debuged it with break point and i noticed that web method doesn't work. And here is the error that i get: DataTables warning: table id=questTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
Thanks in advance.
Problem solved. It was about my web method returns object array and data tables doesn't accept it. That's why i got Invalid JSON response. error. So i change my js structure. I post data as usual then i use data tables data property for post. It works:
function GetData()
{
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'Question.aspx/Questions',
data: '{}',
success: function (result) {
$('#questTable').DataTable({
data:result.d,
columns: [
{ data: 'q_id' },
{ data: 'q_text' },
{ data: 'q_group' }
]
});}
}

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.

Ext JS: Load single database entry into model

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

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

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