How to load json data from ajax in ExtJs - ajax

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

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

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

ExtJs - How to load json file using extjs with the Ext.Ajax.request method?

I wish to load a json file using extjs. Previously I was loading my json file with the help of jquery library as below:
Ext.define('app.store.Students', {
extend: 'Ext.data.Store',
model: 'app.model.Student',
storeId: 'StudentData',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'data/users.json',
success: function(resp) {
console.log(resp.responseText);
},
reader: {
type: 'json',
root: 'student1',
model: 'app.model.Student',
successProperty: 'success'
}
}
});
But now I want to load my json file using ExtJs. I tried the below code:
Ext.define('app.store.Students', {
extend: 'Ext.data.Store',
model: 'app.model.Student',
storeId: 'StudentData',
autoLoad: true,
});
Ext.Ajax.request({
url: 'data/users.json',
//method: 'GET',
success: function(response){
var text = response.responseText;
alert('1')
console.log(this.url);
// process server response here
}
});
but it says 'Uncaught TypeError: Cannot call method 'indexOf' of undefined'. When inspected in firebug, the url given below is undefined in ext-all-debug.js.
urlAppend : function(url, string) {
if (!Ext.isEmpty(string)) {
return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
}
return url;
},
I tried to console the url as given above in Ext.Ajax.request method, it says url is undefined. Where am I going wrong?
FYI: This is my file structure:
-html file
-data folder - users.json
-app folder - store folder - js file (This is where I use my Ext.Ajax.request method)
Am I going wrong in the relative path? If so, how I should use it?
If data is not specified, and if autoLoad is true or an Object, this store's load method is automatically called after creation.Either set autoLoad to false or use proxy with type ajax and reader and then a callback function to handle your json data.
Update : Try this
Ext.define('app.store.Students', {
extend: 'Ext.data.Store',
model: 'app.model.Student',
storeId: 'StudentData',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'app/data/users.json',
reader:{
type: 'json',
root: 'student1'//If you are using student1 as root.
}
}

Kendo Datasource Transport custom function not getting called

Im experiencing a rather annoying bug (?) in Kendo UI Datasource.
My Update method on my transport is not getting called when I pass a custom function, but it does work if I just give it the URL.
This works:
...
transport: {
update: { url: "/My/Action" }
}
...
This does not
...
transport: {
update: function(options) {
var params = JSON.stringify({
pageId: pageId,
pageItem: options.data
});
alert("Update");
$.ajax({
url: "/My/Action",
data:params,
success:function(result) {
options.success($.isArray(result) ? result : [result]);
}
});
}
}
...
The function is not getting invoked, but an ajax request is made to the current page URL, and the model data is being posted, which is rather odd. Sounds like a bug to me.
The only reason I have a need for this, is because Kendo can't figure out that my update action returns only a single element, and not an array - so, since I dont want to bend my API just to satisfy Kendo, I though I'd do it the other way around.
Have anyone experienced this, and can point me in the right direction?
I also tried using the schema.parse, but that didn't get invoked when the Update method was being called.
I use myDs.sync() to sync my datasource.
Works as expected with the demo from the documentation:
var dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: "http://demos.kendoui.com/service/products",
dataType: "jsonp",
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
alert(1);
// make JSONP request to http://demos.kendoui.com/service/products/update
$.ajax( {
url: "http://demos.kendoui.com/service/products/update",
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
// send the updated data items as the "models" service parameter encoded in JSON
data: {
models: kendo.stringify(options.data.models)
},
success: function(result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
schema: {
model: { id: "ProductID" }
}
});
dataSource.fetch(function() {
var product = dataSource.at(0);
product.set("UnitPrice", product.UnitPrice + 1);
dataSource.sync();
});
Here is a live demo: http://jsbin.com/omomes/1/edit

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

Resources