Passing values from Store to the PHP - sencha-touch

I am trying to pass a value to the PHP server side. My Store code is as follows;
Ext.define('MyApp.store.MyArrayStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.MyMOD'
],
config: {
autoLoad: true,
model: 'MyApp.model.MyMOD',
storeId: 'MyArrayStore',
proxy: {
type: 'ajax',
actionMethods: 'POST',
url: 'http://localhost/mm/app/php/res.php',
reader: {
type: 'json'
}
},
listeners: [
{
fn: 'onArraystoreBeforeLoad',
event: 'beforeload'
}
]
},
onArraystoreBeforeLoad: function(store, operation, eOpts) {
this.proxy.extraParams.VALUES1 = "pass some name here";
}
});
PHP Code
<?php
error_reporting(E_ERROR | E_PARSE);
require_once 'conn.php'; // contains the connection
$v = $_POST['VALUES1'];
echo json_encode($v);
?>
What gets returned is null, and not the value that i am passing from the store (which is pass some name here).
How can i correct this ?
UPDATE
Request URL:http://localhost/test/app/php/res.php?_dc=1373343459447
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:23
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost
Origin:http://localhost
Referer:http://localhost/test/app.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parametersview sourceview URL encoded
_dc:1373343459447
Form Dataview sourceview URL encoded
page:1
start:0
limit:25
Response Headersview source
Connection:Keep-Alive
Content-Length:24
Content-Type:text/html
Date:Tue, 09 Jul 2013 04:17:39 GMT
Keep-Alive:timeout=5, max=96
Server:Apache/2.2.14 (Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By:PHP/5.3.1

You need to change the way you setting extraParams.. in this case i will using
store.getProxy().setExtraParam('VALUES1','pass some name here');
If you need to send more than one parameter then use setExtraParams
var param = { VALUES1: 'param1', VALUES2 : 'param2'};
store.getProxy().setExtraParams(param);
So full Store code
Ext.define('MyApp.store.MyArrayStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.MyMOD'
],
config: {
autoLoad: true,
model: 'MyApp.model.MyMOD',
storeId: 'MyArrayStore',
proxy: {
type: 'ajax',
actionMethods: 'POST',
url: 'http://localhost/mm/app/php/res.php',
reader: {
type: 'json'
}
},
listeners: [
{
fn: 'onArraystoreBeforeLoad',
event: 'beforeload'
}
]
},
onArraystoreBeforeLoad: function(store, operation, eOpts) {
store.getProxy().setExtraParam('VALUES1 ','pass some name here');
}
});

Instead of this.proxy try this.getProxy().
I find the console very useful for this sort of thing. In my own app running Ext.getStore('MyStore').proxy; gets me undefined whereas Ext.getStore('MyStore').getProxy() gets me my proxy.
Use the console, for me it is the most valuable development tool next the API.
Good luck, Brad

Related

React native sending image to server using formdata

I have a problem sending a picture to a server, that's like the default approach, but it does not seem to work.
var source = '/Users/alexx/Library/Developer/CoreSimulator/Devices/44F0FA92-4898-4CFB-862E-4E5EC4C8AB28/data/Containers/Bundle/Application/34BCE695-4B4F-472F-AB5C-F2336AC45273/DoorLock.app/123.jpg';
const form = new FormData();
form.append('image', {
uri: source,
type: 'image/jpg',
name: '123.jpg',
});
const data = () => {
fetch(api ,{
method: 'POST',
body: form,
})
that's the response i get from the server:
{
"_bodyBlob": {
"_data": {
"__collector": [
Object
],
"blobId": "78B18938-15BF-4F18-B3C8-1EB30A24D9F8",
"name": "test.html",
"offset": 0,
"size": 192,
"type": "text/html"
}
},
"_bodyInit": {
"_data": {
"__collector": [
Object
],
"blobId": "78B18938-15BF-4F18-B3C8-1EB30A24D9F8",
"name": "test.html",
"offset": 0,
"size": 192,
"type": "text/html"
}
},
"bodyUsed": false,
"headers": {
"map": {
"connection": "keep-alive",
"content-length": "192",
"content-type": "text/html",
"date": "Mon, 02 Nov 2020 22:57:21 GMT",
"server": "PythonAnywhere"
}
},
"ok": false,
"status": 400,
"statusText": undefined,
"type": "default",
"url": api
}
Although this python code works perfectly and gets a correct response
img = {'file':('123.png', open('the path to the pic/123.png', 'rb'), 'image/png)}
post(api, files = img)
is there any way to get this working or its the server side problem that can't receive the correct arguments?
Adding "file://" to the beginning of the source string fixed the problem.
so the src looks like
var source = 'file:///Users/alexx/Library/Developer/CoreSimulator/Devices/44F0FA92-4898-4CFB-862E-4E5EC4C8AB28/data/Containers/Bundle/Application/34BCE695-4B4F-472F-AB5C-F2336AC45273/DoorLock.app/123.jpg';
then it fetches perfectly, hope it helps anybody who tries to send a local image using formdata, the summary looks like this now
const form = new FormData();
form.append('file', {
uri: source,
name: '123.jpg',
fileName: 'file', //optional
});
fetch(uri,{
method: 'post',
body: form,
})
.then(response => {
console.log("image uploaded")
console.log(response)
})
.catch(console.log);
In Formdata when you pass files, you need to pass 3 parameters where
key expected from the backend (in your case image).
It will be an object which has three properties named name, type, and uri where type is the mime type (ex: image/jpeg).
name of the file
Eg:
data.append("FilePath",{
name:"image.png",
type:"image/png",
uri:"content://com.camera/image.png"
},image.png)

API Gateway POST method working during tests, but not with postman

i will try to explain my problem clearly.
I have an API who writes something in DynamoDB with a lambda function written in Node.js. When i'm calling it within the AWS console, the API works as expected. I send a body like that:
{
"user-id":"4dz545zd",
"name":"Bush",
"firstname":"Gerard",
}
And that creates the entry within my dynamoDB table. But when i call the same API (freshly deployed) with Postman, i get this error:
{
"statusCode": "400",
"body": "One or more parameter values were invalid: An AttributeValue may not contain an empty string",
"headers": {
"Content-Type": "application/json"
}
}
When i check in cloudwatch why it fails, i see:
Method request body before transformations: [Binary Data]
This is weird, because i sent JSON with the two headers:
Content-Type:application/json
Accept:application/json
And then in cloudwatch, i see that being processed is:
{
"user-id":"",
"name":"",
"firstname":"",
}
Thats explains the error, but i don't understand why when i'm sending it with postman, being not empty, with the json format, it still sends it as "binary" data, and so not being processed by my mapping rule (And so lambda processing it with an empty json):
#set($inputRoot = $input.path('$'))
{
"httpMethod": "POST",
"body": {
"TableName": "user",
"Item": {
"user-id":"$inputRoot.get('user-id')",
"name":"$inputRoot.get('name')",
"firstname":"$inputRoot.get('firstname')",
}
}
}
Thank you in advance !
EDIT: I'm adding the lambda code function
'use strict';
console.log('Function Prep');
const doc = require('dynamodb-doc');
const dynamo = new doc.DynamoDB();
exports.handler = (event, context, callback) => {
const done = (err, res) => callback(null, {
statusCode: err ? '400' : '200',
body: err ? err.message : res,
headers: {
'Content-Type': 'application/json'
},
});
switch (event.httpMethod) {
case 'DELETE':
dynamo.deleteItem(event.body, done);
break;
case 'HEAD':
dynamo.getItem(event.body, done);
break;
case 'GET':
if (event.queryStringParameters !== undefined) {
dynamo.scan({ TableName: event.queryStringParameters.TableName }, done);
}
else {
dynamo.getItem(event.body, done);
}
break;
case 'POST':
dynamo.putItem(event.body, done);
break;
case 'PUT':
dynamo.putItem(event.body, done);
break;
default:
done(new Error(`Unsupported method "${event.httpMethod}"`));
}
};
That's because when testing from AWS Lambda's console, you're sending the JSON you actually expect. But when this is invoked from API Gateway, the event looks different.
You'll have to access the event.body object in order to get your JSON, however, the body is a Stringified JSON, meaning you'll have to first parse it.
You didn't specify what language you're coding in, but if you're using NodeJS you can parse the body like this:
JSON.parse(event.body).
If you're using Python, then you can do this:
json.loads(event["body"])
If you're using any other language, I suggest you look up how to parse a JSON from a given String
That gives what you need.
This is what an event from API Gateway looks like:
{
"path": "/test/hello",
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, lzma, sdch, br",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
"X-Forwarded-For": "192.168.100.1, 192.168.1.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"pathParameters": {
"proxy": "hello"
},
"requestContext": {
"accountId": "123456789012",
"resourceId": "us4z18",
"stage": "test",
"requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
"identity": {
"cognitoIdentityPoolId": "",
"accountId": "",
"cognitoIdentityId": "",
"caller": "",
"apiKey": "",
"sourceIp": "192.168.100.1",
"cognitoAuthenticationType": "",
"cognitoAuthenticationProvider": "",
"userArn": "",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"user": ""
},
"resourcePath": "/{proxy+}",
"httpMethod": "GET",
"apiId": "wt6mne2s9k"
},
"resource": "/{proxy+}",
"httpMethod": "GET",
"queryStringParameters": {
"name": "me"
},
"stageVariables": {
"stageVarName": "stageVarValue"
},
"body": "'{\"user-id\":\"123\",\"name\":\"name\", \"firstname\":\"firstname\"}'"
}
EDIT
After further discussion in the comments, one more problem is that the you're using the DynamoDB API rather than the DocumentClient API. When using the DynamoDB API, you must specify the types of your objects. DocumentClient, on the other hands, abstracts this complexity away.
I have also refactored your code a little bit (only dealing with POST at the moment for the sake of simplicity), so you can make use of async/await
'use strict';
console.log('Function Prep');
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event) => {
switch (event.httpMethod) {
case 'POST':
await dynamo.put({TableName: 'users', Item: JSON.parse(event.body)}).promise();
break;
default:
throw new Error(`Unsupported method "${event.httpMethod}"`);
}
return {
statusCode: 200,
body: JSON.stringify({message: 'Success'})
}
};
Here's the Item in DynamoDB:
And this is my Postman request:
With proper headers:
When creating API Gateway, I checked the box Use Lambda Proxy integration. My API looks like this:
If you reproduce these steps it should just work.
I got the exact same problem, the solution for me was deploying the api to make my changes available through Postman !
Hope it helps, even one year later
you need to deploy your Amazon API Gateway!!! It took me forever to figure this out, than
Deploy API
I encountered the same problem while working with java and I fixed it by just checking the Use Lambda Proxy integration for POST method.

Cannot use JSONP with specific url

Why i can't use JSONP Store with this url http://www.sozler.im/rest/categories
When i am trying on Sencha Architect, right click on Store/Load Data it gives an error, but it works on browser
Here is the source
Ext.define('SozlerimMobile.store.CategoryStore', {
extend: 'Ext.data.Store',
requires: [
'SozlerimMobile.model.Categories',
'Ext.data.proxy.JsonP',
'Ext.data.reader.Json'
],
config: {
autoLoad: true,
autoSync: true,
model: 'SozlerimMobile.model.Categories',
storeId: 'CategoryStore',
proxy: {
type: 'jsonp',
extraParams: {
Status: 'Active'
},
url: 'http://www.sozler.im/rest/categories/',
reader: {
type: 'json',
clientIdProperty: 'id',
idProperty: 'id',
rootProperty: ''
}
}
}
});
The webservice has to return JSONP (JSON with function callback - see http://json-p.org/)
The more info can be found in: https://stackoverflow.com/a/2067584/282834

Get a particular value from Store in Sencha Touch?

I've created a model with following structure:
Model Code:
Ext.define('MyApp.model.FavoriteScreen', {
extend: 'Ext.data.Model',
config: {
fields: [
{
name: 'Name'
},
{
name: 'ScreenId'
}
]
}
});
And I've created a store with following structure:
Store code:
Ext.define('MyApp.store.FavoriteStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.FavoriteScreen'
],
config: {
autoLoad: true,
model: 'MyApp.model.FavoriteScreen',
storeId: 'FavStore',
proxy: {
type: 'ajax',
api: {
read: '/api/sample/FavoriteList'
},
headers: {
'Content-Type': 'application/json; charset=UTF-8'
},
reader: {
type: 'json',
rootProperty: 'data'
}
}
}
});
Now I want to get particular record from this store but my store does not return any value. To get value from store I've written following line of code:
var myStore = Ext.getStore('FavStore');
myStore.load({
scope: this,
callback: function (records, operation, success) {
if (success) {
Ext.Msg.alert(myStore.getAt(0).getData());
}
}
});
The above code I've written on The above code I’ve written on nestedlistleafitemtap event.
Any help is appreciated!!
First of all - don't use getData() - use get('name') for example.
Second - try to add logging before your loading call and inside your callback function. This way you can see whether you started loading and was it completed.

JSON response not parsed

I'm developing an app in Sencha Touch 2.0 that is supposed to parse JSON through a web service that resides on a different domain.
I'm stuck parsing JSON. If I use nodes with names like title, author description link etc then it works perfectly.
But if I use other names for nodes then it does not display anything.
Here is the JSON response I'm trying to parse:
http://stassuet.byethost15.com/services/test/index.php
This is what I'm doing to parse the response in Sencha app:
Ext.define('GS.store.MyStore', {
extend: 'Ext.data.Store',
requires: [
'GS.model.MainEvent',
'Ext.data.proxy.JsonP',
'Ext.data.proxy.Rest'
//'GS.util.JsonpX'
],
config: {
autoLoad: true,
model: 'GS.model.MainEvent',
storeId: '55',
headers: {
"Accept": "text/xml"
//"access-control-allow-origin": "*",
//"Origin": "goodnews.pk",
//"Referer": "goodnews.pk"
},
method: 'GET',
callbackKey: 'myFunction',
proxy: {
type: 'jsonp',
url: 'http://stassuet.byethost15.com/services/test/index.php',
reader: {
type: 'json',
rootProperty: 'albums.images'
}
}
}
});
Where am I going wrong?
You seem to have a lot of configurations set even though you don't need them. For example:
headers
method
callbackKey
Is there a reason for this?
Anyway, using this class, everything loads as it should:
Ext.define('Example.store.SO', {
extend: 'Ext.data.Store',
config: {
autoLoad: true,
fields: [
'name',
'author',
'last_modified'
],
proxy: {
type: 'jsonp',
url: 'http://stassuet.byethost15.com/services/test/index.php',
reader: {
rootProperty: 'albums.images'
}
}
}
});