how to access post parameters in php? - extjs

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.

Related

ExtJs (6.0.0) rest service PUT request

I am trying to PUT some data from my frontend (ExtJs) into my backend (Java, Spring). It does not work or I do not get the right clue...
I am on a Ext.grid.Panel where I use the following store which is (nicely) filled and displayed by a this.store.setData( myObject.data.items ) method:
Ext.define( 'NameOfThisClass', {
extend: 'Ext.grid.Panel',
...
store: Ext.create( 'Ext.data.Store', {
data: [],
autoLoad: false,
proxy: {
type: 'rest',
url: '/somepath/theclass',
reader: {
type: 'json',
rootProperty: 'data',
totalProperty: 'totalCount'
},
writer: {
type: 'json'
},
}
} ),
...
// setting the data to be visualized
setValue: function(myObject) {
this.store.setData( myObject.data.items );
}
...
updateRecord: function(objectId, objectWithUpdateProperties) {
// do what with the store and/or proxy?
}
...
});
I display all entries in a table. The entries are not automatically loaded by the store but set from outside: setValue(myObject).
There is another store for initially loading the data. The data received is then splittet and forwarded in order not to have several requests.
I do get a nice visualized table whose entries are editable by the rowediting plugin.
Ok, so far the backgrounds.
When editing the table's data I run through some validations and gather more data via a modal dialog and then I have the data in order to send to the server by a call of updateRecord(objectId, objectWithUpdateProperties).
This sending is my problem. I do not know how to call/send a rest/put request which will be read by the server. (Receiving is not the problem, sending is).
I guess I somewhat need to trigger my store or the store's proxy. But how?
It is not that I can simply tell my object to save since I do have more data than just the changed object's properties.
Can anyone help me here?
I normally use Ext.Ajax to achieve that, like this:
updateRecord: function(objectId, objectWithUpdateProperties) {
Ext.Ajax.request({
url: 'YourUrl',
params: {
some_param: 'some_value',
object_id: objectId,
object_with_properties_param1: objectWithUpdateProperties.param1
},
success: function(response, opts) {
//Horay, Do something with the response
},
failure: function(response, opts) {
//Oh nooooo
}
});
}
Don't need to use Ajax.
You need to config proxy.api CRUD(C:create, R:read, U:Update. D:Delete) on RestProxy, from client side.
Also, store must have autoSync:true.
At server side, need to config a #RestController for each one of CRUD (with JSON-Java encoder for parameters like Jackson or equivalent), that will acept JSON data. Take into account, that you may send only modified field (store.proxy.writer.writeAllFields: false ->>> default) or just the full record (.writeAllFields:true) to server.
Here an example (inside store's constructor):
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: true,
autoSync: true,
model: 'Test.model.Country',
proxy: {
type: 'rest',
api: {
create: 'country/create',
read: 'counrtry/list'
update: 'counrtry/update',
destroy: 'counrtry/destroy'
},
writer:{
writeAllFields : true
},
reader:{
root:'items',
totalProperty: 'rowCount'
}
}
}, cfg)]);
}
Extra note: For reading from server and load store automatically, just set store.autoLoad: true, and the corresponding #RestController method from server side. Take into account the store.reader params.

Using Jsonp in proxy in model in extjs 4.2.1

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

Using Extjs Ajax proxy with rails rest server

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!

Can't load json(p) cross-domain with Sencha Touch

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

JSONP not working on ExtJS 4 - Uncaught TypeError: Cannot call method 'substring' of undefined

I'm stuck with this code, I'm getting this json formated data from the Youtube API, if I use type:'json' it will fail, because of that cross domain thing but the other elements loads anyway; then, if I change type: to 'jsonp' (which is the syntax described on the ExtJS API) it would give me this error:"Uncaught TypeError: Cannot call method 'substring' of undefined" I tried setting type:'anyotherstupidthing' and the same happens, so what could be happening?
Here are my current data model and my store:
Ext.define('Video', {
extend: 'Ext.data.Model',
fields: ['id', 'title']
});
myStore2 = Ext.create('Ext.data.Store', {
model: 'Video',
proxy: {
type: 'ajax',
url : 'http://gdata.youtube.com/feeds/api/videos?q=surfing&v=2&alt=jsonc',
reader: {
type: 'jsonp',
root: 'items'
}
}
});
Thanks in advance!
Ed.
JsonP requires the server to wrap the returned data in a JS function call. The common contract is to pass a parameter named 'callback' to the server to allow for unique names and avoid name clashes on the client.
Calling the URL http://gdata.youtube.com/feeds/api/videos?q=surfing&v=2&alt=jsonc&callback=myCallback in the browser shows that YouTube support this convention:
Ext supports JsonP via the Ext.data.proxy.JsonP proxy class. The reader is a standard JSON reader and not JsonP specific, you only need to account for the data structure returned from the server (set root to data.items).
The working code looks like this:
var myStore2 = Ext.create('Ext.data.Store', {
model: 'Video',
proxy: {
type: 'jsonp',
url : 'http://gdata.youtube.com/feeds/api/videos?q=surfing&v=2&alt=jsonc',
reader: {
type: 'json',
root: 'data.items'
}
},
listeners: {
load: function(store, records) {
Ext.each(records, function(rec) {
console.log(rec.get('title'));
});
}
},
autoLoad: true
});

Resources