I'm having a heck of a time trying to load external json into a Sencha Touch app. I can define my data within the app, or with an external json file and all's fine. Then I move my json file to a remove server, change my proxy to type: 'scripttag' to take care of jsonp issues, and then I have issues. When I look at my page resources I see that the json file DID load, but it doesn't populate my list as it does with my local json file.
Using local json file (this works)
var jsonStore = new Ext.data.Store({
model: "Person",
proxy: {
type: 'ajax',
url: 'http://dev.liftstudios.ca/data.json',
reader: {
type: 'json'
}
},
autoLoad: true
});
var jsonPanel = {
title: "json",
items: [
{
xtype: 'list',
store: jsonStore,
itemTpl:itemTemplate,
singleSelect: true
}
]
};
Using the same json file, loaded from a remote host.
This loads the file, but doesn't populate the list.
var jsonStore = new Ext.data.Store({
model: "Person",
proxy: {
type: 'scripttag',
url: 'http://www.server.com/data.json',
reader: {
type: 'json'
}
},
autoLoad: true
});
var jsonPanel = {
title: "json",
items: [
{
xtype: 'list',
store: jsonStore,
itemTpl:itemTemplate,
singleSelect: true
}
]
};
There's probably something embarrassingly simple that I'm missing here, but I'm not sure what that something is. Any help will be greatly appreciated.
Changing the proxy type to scripttag does not make any sense . If you want to load a scripttag store, you have to implement a callback function as well. If you want do make cross platform ajax calls with the existing json proxy , you can test it on the browser by disabling the web security on chrome.
The cross-domain problem can be solved by starting google chrome from the terminal by this command google-chrome --args --disable-web-security
Check out this link for more information
http://www.senchatouchbits.com/7/cross-domain-ajax-requests.html
Hope it will help...
Use type jsonp for proxy type in the store
var jsonStore = new Ext.data.Store({
model: "Person",
proxy: {
type: 'jsonp',
url: 'http://www.server.com/data.json',
reader: {
type: 'json'
}
},
autoLoad: true
});
And Implementing on the server side:
The remote server side needs to be configured to return data in this format. Here are suggestions for how you might achieve this using Java, PHP and ASP.net:
Java:
boolean jsonP = false;
String cb = request.getParameter("callback");
if (cb != null) {
jsonP = true;
response.setContentType("text/javascript");
} else {
response.setContentType("application/x-json");
}
Writer out = response.getWriter();
if (jsonP) {
out.write(cb + "(");
}
out.print(dataBlock.toJsonString());
if (jsonP) {
out.write(");");
}
PHP:
$callback = $_REQUEST['callback'];
// Create the output object.
$output = array('a' => 'Apple', 'b' => 'Banana');
//start output
if ($callback) {
header('Content-Type: text/javascript');
echo $callback . '(' . json_encode($output) . ');';
} else {
header('Content-Type: application/x-json');
echo json_encode($output);
}
ASP.net:
String jsonString = "{success: true}";
String cb = Request.Params.Get("callback");
String responseString = "";
if (!String.IsNullOrEmpty(cb)) {
responseString = cb + "(" + jsonString + ")";
} else {
responseString = jsonString;
}
Response.Write(responseString);
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.proxy.JsonP
var jsonStore = new Ext.data.Store({
model: "Person",
proxy: {
type: 'jsonp',
url: 'http://www.server.com/data.json',
reader: {
type: 'json'
}
},
autoLoad: true,
crossDomain: true,
});
crossDomain: true,try this
Related
I have a grid panel and i want to get data that i embed in store
My json look like (embed is my embed data)
({"total":"20","results":[{...}], "embed": [{...}] })
How to get embed data in my load function. Thanks
var store = Ext.create('Ext.data.Store', {
model: 'MyDataObject',
autoLoad: true,
pageSize:10,
proxy: {
type: 'ajax',
url: 'data.php',
reader: {
type: 'json',
totalProperty: 'total', // total data
root: 'results'
}
}
,listeners: {
load: function( store, records, successful, eOpts ){
if (successful) {
alert(store.embed) // ?? how to get it
}
}
}
});
The proxy keeps a reference to the rawData property for the most recent load.
console.log(store.getProxy().getReader().rawData.embed);
I am calling rest web service from sencha extjs 4.2.1 in model .My model is
Ext.define('AM.model.User', {
extend: 'Ext.data.Model',
fields: [
{name: 'subCategoryName', type: 'string'},
],
proxy:{
type : 'jsonp',
callbackKey: 'callback',
url: 'http://192.168.1.10:8080/CredoCustomerConnect/subcategory/getsubcategorylist/1/1/0',
headers: {
'Accept': 'application/json'
},
callback: function( data ) {
console.log("callback" + data);
},
listeners: {
load: function() {
console.log("in load");
}
},
reader: {
type: 'json',
rootProperty:'subcategory'
}
}
});
When I call the url 'http://192.168.1.10:8080/CredoCustomerConnect/subcategory/getsubcategorylist/1/1/0',
in the browser , I am getting the result like
callback({"listException":"false","listSize":"5","nextPage":"false","pageNumber":"0","subcategory":[{"isException":"false","categoryId":"1","categoryName":"Solutions","productSize":"4","subCategoryDescription":"Oracle Consulting","subCategoryId":"1","subCategoryName":"Oracle Consulting"},],"totalRecords":"5"})
But I am not seeing any data in grid view.
Rest Web service method is
#GET
#Path("getsubcategorylist/{categoryId}/{userId}/{pageNumber}")
#Consumes("application/x-www-form-urlencoded")
//#Produces({MediaType.APPLICATION_JSON})
#Produces({"application/javascript"})
public JSONWithPadding getSubCategorylist(#PathParam("categoryId") int categoryId,#PathParam("userId")int userId,#PathParam("pageNumber") int pageNumber, #QueryParam("callback") String callback)
{
SubCategoryList subCategory = new SubCategoryList();
SubCategoryEntityHandler handler = new SubCategoryEntityHandler();
try {
subCategory = handler.getSubCategoriesList(categoryId,pageNumber);
return new JSONWithPadding(
new GenericEntity<SubCategoryList>(subCategory) {
},callback);
} catch (Exception e) {
e.printStackTrace();
subCategory.setListException(true);
subCategory.setListMessage(e.getMessage());
return new JSONWithPadding(
new GenericEntity<SubCategoryList>(subCategory) {
}, "callback");
}
}
My store is
Ext.define('AM.store.Users', {
extend: 'Ext.data.Store',
config: {
model: 'AM.model.User',
}
});
My view is
Ext.define('AM.view.user.List' ,{
extend: 'Ext.grid.Panel',
alias: 'widget.userlist',
title: 'All Users',
store: 'Users',
initComponent: function() {
this.columns = [
{header: 'Subject', dataIndex: 'subCategoryName', flex: 1},
];
this.callParent(arguments);
}
});
There is no error in console. But I am not seeing any data in grid.
How to resolve this?
Your server should not return simply:
callback({...})
Instead, it must read the value of the request GET param you've configured as callbackKey (in your case, that's 'callback'), and use this value as the name of the callback in the response. See section "Implementing on the server side" in the JsonP proxy doc.
For example, for its first request, the proxy will use an URL like this:
http://192.168.1.10:8080/CredoCustomerConnect/subcategory/getsubcategorylist/1/1/0?callback=Ext.data.JsonP.callback1
So the server response must be:
Ext.data.JsonP.callback1({ ... })
The second request URL would be something like:
http://192.168.1.10:8080/CredoCustomerConnect/subcategory/getsubcategorylist/1/1/0?callback=Ext.data.JsonP.callback2
Etc, etc.
From Extjs docs:
JsonP proxy creates a temporary callback function, waits for it to be
called and then puts the data into the Proxy making it look just like
you loaded it through a normal AjaxProxy.
This code worked for me after a bit of tweaking around
Ext.define('My.Model', {
extend: 'Ext.data.Model',
fields: [
'id', 'name'
],
proxy:{
type : 'jsonp',
url: 'http://127.0.0.1:8080',
reader : {
type : 'json',
root : 'data'
}
}
My.Model.load(1, {
callback: function(data) {
console.log(data);
}
});
Server side:
// Retrieve the callback parameter
cb = parms.get("callback");
// Build response string
msg = cb + "({ \"data\": [{\"id\": 1, \"name\": \"" + "username" + "\"}] });";
//Return msg with status 200 OK and "text/javascript" header
I am working in Extjs4 plus yii framework and using MVC structure. I am going to send data from extjs4 to yii framework. I am using post method to send data to server side, but I am not yet succeed to display data in yii framework. When I am using get() method the data accessed to yii framework side easily. Actually I dont want to display data in url so thats why I am using post() method in extjs4.
Here is my some code:
Model file:
Ext.define('Bal.model.sn.UserModel', {
extend: 'Ext.data.Model',
//idproperty:'userId',//fields property first position pk.
fields: ['userId', 'firstName', 'middleName', 'lastName', 'languageId', 'primaryEmail', 'birthDate', 'password', 'securityQuestionId', 'securityQuestionAnswer', 'isMale', 'creationTime', 'ipAddress', 'confirmationCode', 'userStatusId', ]
});
Store file:
Ext.define('Bal.store.sn.UserStore', {
extend: 'Ext.data.Store',
model: 'Bal.model.sn.UserModel',
//autoLoad: true,
proxy: {
type: 'ajax',
api: {
read: 'http://localhost/balaee/Balaee/index.php/SocialNetworking/user/AuthenticateLogin',
create: 'http://localhost/balaee/Balaee/index.php/SocialNetworking/user/AuthenticateLogin',
//update: ,
//destroy: ,
}, //End of api
extraParams: {
hello: 'Inside store',
},
actionMethods: {
create: 'POST',
read: 'POST',
update: 'POST',
destroy: 'POST'
},
reader: {
type: 'json',
//root: ,
//successProperty: ,
}, //End of reader
writer: {
type: 'json',
root: 'records',
}, //End of writer
} //End of proxy
}); //End of store
My controller file some code:
var obj = this.getStore('sn.UserStore');
obj.load({
params: {
hello: 'jitu'
}
});
And here is my yii framework controller file code:
$postData = json_decode(file_get_contents("php://input"), true);
$clientData = $postData['records'];
echo $_POST['hello'];
How can I display this hello parameter in yii framework? Please give some suggestion.
I use something like this. if $_POST['PostDataName'] is empty getPost($name) returns NULL
public function actionFoo()
{
$data = Yii::app()->request->getPost('PostDataName');
}
What error you are getting. Like 400, 404, 500 etc. Also do you have CSRF enabled in your YII app. If not then something like this should do.
public function actioTest()
{
$post = $_POST['hello'];
}
If CSRF is enabled then you have to pass CSRF value with the request as well.
I'm trying to call via GET method, my server action /users/menus, but it seams to work only with REST proxy.
Here is my store declaration:
Ext.define('App.store.Menu', {
extend: 'Ext.data.Store',
model: 'App.model.Menu',
proxy: {
type: 'ajax',
reader: {
type: 'json'
},
api: {
read: 'users/menus'
}
}
});
and here is how I load the store:
var store = Ext.create('App.store.Menu').load({
id: 1,
callback: function () {
//do something...
}
});
and this is my rails code:
def menus
#user = User.find(params[:id])
#menus = #user.menus
respond_to do |format|
format.html # menus.html.erb
format.json { render json: #menus }
end
end
I get this error on the server:
ActiveRecord::RecordNotFound (Couldn't find User with id=menus):
app/controllers/users_controller.rb:16:in `show'
But if I use REST proxy, I get correct request:
Ext.define('App.store.Menu', {
extend: 'Ext.data.Store',
model: 'App.model.Menu',
proxy: {
type: 'rest',
format: 'json',
url: 'users/menus'
}
});
That is because your url schema is a REST schema and then you should use a rest proxy. This is how both proxies send the Id value:
Ajax proxy: yourdomain.com/users/menus?id=1
Rest proxy: yourdomain.com/users/menus/1
There is no reason to use and ajax proxy when your application understand a rest schema. However, if you want to force things in order to be able to use an ajax request, you can modify your proxy as follow:
Ext.define('App.store.Menu', {
extend: 'Ext.data.Store',
model: 'App.model.Menu',
proxy: {
type: 'ajax',
url: 'users/menus',
reader: {
type: 'json'
},
buildUrl: function(request) {
debugger;
var me = this,
url = me.getUrl(request),
operation = request.operation,
id = operation.id;
if (id) {
if (!url.match(/\/$/)) {
url += '/';
}
url += id;
}
return url;
}
}
});
This does something similar that rest proxy but it is an ajax proxy.
Good luck!
I am using following code:
var genres1 = new Ext.data.Store({
reader: new Ext.data.JsonReader({
fields: ['pincode','place_name'],
root: 'rows'
}),
proxy: new Ext.data.HttpProxy({
url: 'pointalong.php',
method: 'GET'
})
});
but i want to pass 3 parameters to my php file. how should i proccess? and also how would i get at php file.
There are two possibilities. The first one is to use store baseParams config:
var genres1 = new Ext.data.Store({
baseParams: {
param1: 'value1',
param2: 'value2'
},
// ...
The second one is to send them when you are using load method:
genres1.load({params: {param2: 'anotherValue'}});
Note: params will override any baseParams of the same name
So if you setup store with baseParams like in example above and then use load with params the store will request ...?param1=value1¶m2=anotherValue.
... and also how would i get at php file
As usual variable passed via the URL parameters - using $_GET:
$param1 = $_GET['param1'];
I use this and it works perfectly
Ext.define('store.odon.DiagnosticoStore', {
extend : 'Ext.data.Store',
model : 'model.odont.DiagnosticoModel',
proxy: {
type: 'ajax',
api: {
create: CONTEXT_PATH + '/mvc/odona/crear',
read: CONTEXT_PATH + '/mvc/odon/lista',
update: CONTEXT_PATH + '/mvc/odon/update',
destroy: CONTEXT_PATH + '/mvc/odon/delete'
},
reader: {
type: 'json',
root: 'diagnosticos',
successProperty: 'success'
},
writer: {
type: 'json',
writeAllFields: true,
encode: true,
root: 'diagnosticos'
}
}
});
the parameter is assigned to load the store
var storeDiagnostico= getStore(); // Ext.create('store.odon.DiagnosticoStore');
storeDiagnostico.getProxy().setExtraParam("idOdontologia", value);
storeDiagnostico.load();
If the value of the parameter may change (for example, if it comes from another form field), then the most reliable way is to apply the proxy parameter before the load event each time the store loads, as follows:
Ext.create('Ext.data.Store', {
...
listeners:{
beforeload: function(store){
var filterText = Ext.getCmp('filterText').value;
store.getProxy().setExtraParam("filterText", filterText);
}
},