Getting data from web service using ajax - ajax

I'm trying to get data from a webservice using ajax and POST method.
Ext.Ajax.request({
url: 'http://localhost......',
method:'POST',
success: function(response) { console.log(response.responseText); },
failure: function() { Ext.Msg.alert('Fail'); },
jsonData:{
/*Here I specify my request json*/
}
}
});
The above thing works fine but when i try to mimic the same in EXTJS store it responds with a error
he server responded with a status of 415 (Unsupported Media Type)
EXTJS STORE CODE
Ext.define('IWM.store.JsonTest', {
extend: 'Ext.data.Store',
autoLoad: true,
fields:['Name'],
proxy: {
type: 'ajax',
method : 'POST',
actionMethods: {
create : 'POST',
read : 'POST',
update : 'POST',
destroy: 'POST'
},
jsonData:{
/*JSON */
}
},
url: 'http://localhost......',
success: function(response) { console.log(response.responseText); },
failure:function(){console.log("failed");},
reader: {
type: 'json',
root: 'result',
successProperty: 'success'
}
}
});

First things first, try to change store config as below.
var IWMStore = new Ext.data.JsonStore({
// it seems to me you had forgotten model
model: 'YourDataModel',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'http://your-url-address',
reader: {
type: 'json',
root: 'json-root-value',
idProperty: 'unique-property-in-json-file'
}
}
});
Example JSON value :
// here, ctgMains is the root value, CUST_ASSORT_SECTION_ID is the idProperty
{"ctgMains":[{"CUST_ASSORT_SECTION_ID":"1","CTG_SECTION":"HORECA"},{"CUST_ASSORT_SECTION_ID":"7","CTG_SECTION":"SCO"},{"CUST_ASSORT_SECTION_ID":"3","CTG_SECTION":"TRADER"}]}
Second Attempt :
Try to add headers property in your proxy definition, like below:
proxy: {
type: 'ajax',
url: 'http://your-url-address',
reader: {
type: 'json',
root: 'json-root-value',
idProperty: 'unique-property-in-json-file'
},
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
}
}

Following on from Oğuz Çelikdemir's answer, you may need to define a json writer for your proxy.
proxy: {
type: 'ajax',
url: 'http://your-url-address',
reader: {
type: 'json',
root: 'json-root-value',
idProperty: 'unique-property-in-json-file'
},
writer: {
type: 'json'
}
}
That should set the json mediatype header (assuming that's what your request is expecting).

Related

Ext JS store sync change method

Is it possible to change the dafault methos POST that a store snync() request uses.
I have tried the following but it did not work. I would like to change the method from POST to PUT.
I am aware I can write a custom Ajax request but is there a way to do this with the store sync() functionallity?
store.sync({
method: 'PUT',
scope:this,
callback: function(batch, options){
},
success : function(batch, options) {
},
failure : function(batch, options) {
}
});
}
I have also tried this kind of approach without success:
store.getProxy().method = 'PUT';
In the proxy config for your store, you can configure the api to make specific request methods for each type of action.
For example:
proxy: {
type: 'ajax',
actionMethods: {
create: 'POST',
read: 'GET',
update: 'POST',
destroy: 'POST'
},
batchActions: false,
api: {
create: 'foo/sample.json',
read: 'bar/sampleB.json',
update: 'test/test.json',
destroy: 'admin/testa.json'
},
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json'
}
}
EDIT
The code above gets generated from Sencha Architect, but if you are not using Architect you could define the api actions on your REST proxy like this:
proxy: {
type: 'rest',
api: {
create: {url: 'foo/sample.json', method: 'POST'},
read: {url: 'bar/sampleB.json', method: 'GET'},
update: {'test/test.json', method: 'PUT'},
destroy: {'admin/testa.json', method: 'POST'}
}
}

Kendo DataSource reads my remote database but won't save things to it

It can Read the remote database, it can Create new items locally, but they don't actually save to the remote database. This is what adds a new item:
function addNewItem(){
dataSource.add({id:"0", petName:"Dusty", petSpecies:"Dog", petGender:"M"});
dataSource.sync();
}
$('#addPet').bind('click', addNewItem);
This ajax POST call in that function instead of the dataSource stuff adds to my database perfectly:
var object = { id:"0", petName:"Dusty", petSpecies:"Dog", petGender:"M" };
$.ajax({
type: "POST",
url: 'website/petData',
headers: { "Authorization" : "Bearer ${AccessToken}" },
contentType: "application/json",
data: JSON.stringify(object)
})
Here is my datasource code. What do I need to change? I've tried doing sooooo many different things but no luck yet.
var dataSource = new kendo.data.DataSource({
type: "everlive",
transport: {
typeName: 'petData',
read: {
url: "website/petData",
dataType: "jsonp"
},
create: {
url: 'website/petData',
dataType: "jsonp"
}
},
group: "petSpecies",
schema: {
model: {
id: "id",
fields: {
id: { type: "number"},
petName: { type: "text" },
petSpecies: { type: "text" },
petGender: { type: "text" }
}
}
}
});
So thanks to giltnerj0 and Brett's comments, I was able to google the right words, and discovered that all I needed to do was change create's dataType:jsonp to json. I'm getting some POST errors now, but it's POSTing finally and saving things to my database.
create: {
url: 'website/petData',
dataType: "json"
}

Differences between using json and jsonP

i had a simple controller to update my truck list in my db. Iniatially it had been working with jsonP(because my server was in another domain), and it worked fine, but then i had joined the php scripts(to manage crud in db) in the same domain and i had changed to ajax proxy. The problem is that i had noticed although ajax proxy sends POST request... i never get anything... (These never occurs with jsonp, because it sent GET request i think). So, is there anything i had forgotten or i must do?
Let me show my store before and after the upgrade:
BEFORE:
Ext.define('myapp.store.ListaCamiones', {
extend: 'Ext.data.Store',
requires: [
'myapp.model.Camion'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: true,
autoSync: true,
model: 'myapp.model.Camion',
storeId: 'ListaCamiones',
proxy: {
type: 'jsonp',
api: {
read: 'http://myapp.localhost/camion/listar',
write: 'http://myapp.localhostt/camion/guardar/',
update: 'http://myapp.localhost/camion/guardar/',
destroy: 'http://myapp.localhost/camion/eliminar/'
},
url: 'http://myapp.localhost/camion/listar',
reader: {
type: 'json',
root: 'listacamion'
},
writer: {
type: 'json',
root: 'listacamion'
}
}
}, cfg)]);
}
});
AFTER:
Ext.define('myapp.store.ListaCamiones', {
extend: 'Ext.data.Store',
requires: [
'myapp.model.Camion'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: true,
autoSync: true,
model: 'myapp.model.Camion',
storeId: 'ListaCamiones',
proxy: {
type: 'ajax',
url: '/camion/listar',
api: {
read: '/camion/listar',
write: '/camion/guardar/',
update: '/camion/guardar/',
destroy: '/camion/eliminar/'
},
reader: {
type: 'json',
root: 'listacamion'
},
writer: {
type: 'json',
root: 'listacamion'
}
}
}, cfg)]);
}
});
This is what i got from chrome debug:
Connection:Keep-Alive
Content-Length:0
Content-Type:application/x-json
Date:Mon, 01 Jul 2013 15:40:38 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.2.22 (Ubuntu)
X-Powered-By:PHP/5.4.9-4ubuntu2
I hope you can help me to understand what is happening . Thank you in advance
try changing your proxy type to 'rest'

Sencha Touch: how to Update data Store to list from controller

am facing problem while updating list from controller. I have store, model and list to show Json data. am able to get data but could not able update the list. and if do the ajax call in my store am able to data with list but listners are not getting called. So i moved the code to controller.
here is my store:
Ext.define('MyApp.store.StoreList', {
extend:'Ext.data.Store',
requires:['MyApp.model.ModelList'],
config:{
model:'MyApp.model.ModelList',
autoLoad:'true',
storeId:'id_StoreList'
}
});
model:
Ext.define('MyApp.model.ModelList', {
extend: 'Ext.data.Model',
xtype:'modelList',
config: {
fields:['name']
}
});
controller
Ext.define('MyApp.controller.Main', {
extend : 'Ext.app.Controller',
requires : ['MyApp.view.MyList'],
config : {
refs : {
loadbtn:'button[action=loadbtn]',
dataList: '#id_listitems'
},
control : {
"#dataList": {
itemtap: 'onListItemTap'
},
loadbtn:{
tap : 'handleloadbtn'
}
}
},
handleloadbtn: function(){
console.log('loadbtn tapped');
Ext.Viewport.setMasked({xtype:'loadmask',message:'loading...'});
this.ajaxCall();
},
ajaxCall:function(){
Ext.Ajax.request({
method: 'POST',
scope: this,
extraParams: {
Details: true
},
url:'http://localhost:9080/works',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
headers :{
"Content-Type" :'application/xml',
'Accept':'application/json'
},
reader:
{
type:'json'
},
success: function(response){
console.log('success');
// var list = Ext.getCmp('id_listitems')
//var store = Ext.getStore('id_StoreList');
var store = Ext.data.StoreManager.lookup('id_StoreList');
this.getDataList().setStore(store);
//Error : Uncaught ReferenceError: getDataList is not defined
console.log('test:',test);
Ext.Viewport.setMasked(false);
}
})
}
});
list:
Ext.define('MyApp.view.MyList',{
extend:'Ext.Panel',
xtype:'myList',
requires:['Ext.dataview.List'],
config:{
layout:'fit',
styleHtmlContent:'true',
styleHtmlCls:'showListCls',
items:[
{
docked:'top',
items:[
{
xtype:'button',
text:'Load',
ui:'Plain',
action:'loadbtn',
width:'180px',
height:'30px',
docked:'right',
margin : '5 15 5 0'
}
]
},
{
xtype:'list',
id: 'id_listitems',
action:'list_Item_Action',
store:'StoreList',
itemTpl:['{name}'
]
}
]
}
});
Can any one please help me out in resolving this? Thanks.
You need to use this.getDataList() like so:
Ext.Ajax.request({
method: 'POST',
extraParams: {
Details: true
},
url:'http://localhost:9080/works',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
headers :{
"Content-Type" :'application/xml',
'Accept':'application/json'
},
reader:
{
type:'json'
},
success: function(response){
console.log('success');
// var list = Ext.getCmp('id_listitems')
//var store = Ext.getStore('id_StoreList');
var store = Ext.data.StoreManager.lookup('id_StoreList');
this.getDataList().setStore(store);
//Error : Uncaught ReferenceError: getDataList is not defined
console.log('test:',test);
Ext.Viewport.setMasked(false);
},
scope: this
});
You also need to add scope: this to your request config object so that this in the success method is not the request but your controller.
Hope this helps.
I think you can try this.
your store would look like
Ext.define('MyApp.store.StoreList', {
extend:'Ext.data.Store',
requires:['MyApp.model.ModelList'],
config:{
model:'MyApp.model.ModelList',
autoLoad:'true',
clearOnPageLoad: false,
proxy: {
type: 'jsonp',
useDefaultXhrHeader: false,
url: 'http://localhost:9080/works',
reader: {
type: 'json',
rootProperty: "Items" //It depends on your json data structure
},
callbackKey: 'callback'
}
}
});
In the Controller "handleloadbtn" function , you can just call
Ext.getStore("StoreList").load(); //despite of the config "autoLoad:true"

I'm having trouble with ExtJS4 passing a querystring (parameter) with store.load

I'm having trouble passing parameters into the GetAll method of my controller. I tried Filter as below but no luck. any suggestions?
Ext.define('AM.store.Sessions', {
extend: 'Ext.data.Store',
model: 'AM.model.Session',
autoLoad: false,
proxy: {
type: 'ajax',
api: {
read: 'Session/GetAll',
update: 'data/updateUsers.json'
},
reader: {
type: 'json',
root: 'Data',
successProperty: 'success'
},
filters: [
new Ext.util.Filter({
property: 'eyeColor',
value: 'brown'
})
]
}
});
Im not sure what you are after. But stating extraParams in you proxy will put that parameter on every load() on your store. Like this.
Ext.define('AM.store.Sessions', {
extend: 'Ext.data.Store',
model: 'AM.model.Session',
autoLoad: false,
proxy: {
type: 'ajax',
api: {
read: 'Session/GetAll',
update: 'data/updateUsers.json'
},
extraParams:{
eyeColor:'brown'
}
reader: {
type: 'json',
root: 'Data',
successProperty: 'success'
}
}
});
You could also listen on the "beforeLoad" event on the store and modifu parameters there.
OR.. you could just pass parameters to the load() function as this
var myStore = Ext.create('AM.store.Session');
myStore.load({
params:{
eyeColor:'brown'
}
})

Resources