Sencha Touch: Using proxy and POST request and URL generation - sencha-touch-2

I have been trying to do a post request using a proxy. I have tried the direct proxy, rest and ajax proxy, and haven't been able to find a working example for a POST request.
Is it possible? Because all the examples that I have seen seen to be using only GET.
Any working examples, or pointers in this direction?
Also, I couldn't figure what is the correct way to generate URLs for a proxy at run-time, for example, calling a function to return the URL.

It appears that this might not be possible:
http://www.sencha.com/forum/showthread.php?205557-Using-Ext.data.proxy.Ajax-via-a-POST-with-jsonData

If you look at the source code for Ext.data.proxy.Rest you'll see a config object for actionMethods. They're not documented, but you should be able to pass that as a config on your proxy to override it.
For example:
proxy: {
type: 'ajax',
url: 'path/to/foo',
actionMethods: {
create : 'POST',
read : 'POST',
update : 'PUT',
destroy: 'DELETE'
},
reader: {
type: 'json',
rootProperty: 'root',
totalProperty : 'totalCount'
}
}

Easiest example of POST request could be like this:
var obj = new Object();
obj.userId = username;
obj.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'http://myservice/auth/login?_type=json', // url : this.getUrl(),
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : data,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
Ext.Msg.alert("Success", "Welcome "+respObj.user.name);
},
failure : function(response) {
var respObj = Ext.JSON.decode(response.responseText);
Ext.Msg.alert("Error", respObj.status.statusMessage);
}
});
Please note here you can customize url as per your convenience.

Related

Amazon Gateway API with Lambda - Could not parse request body into json

I seem to be getting a issue with Amazon Gateway API not liking my sent params for example.
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: {
"device": "test",
"datetime": "1446757400919"
},
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("DOES NOT WORK - <br>" + JSON.stringify(returnhtml));
}
});
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: {},
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("<br>WORKS ???? - <br>" + JSON.stringify(returnhtml));
}
});
Here is a working example.
http://jsfiddle.net/Uwcuz/4315/
Can someone let me know why it wont let me send params every time i add a parameter i get this error.
{
Type = User;
message = "Could not parse request body into json.";
}
OK THIS WORKS BUT SEEMS A BIT WEIRD TO ME.
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: "{\"device\": \"test\",\"datetime\": \"1446757444524\"}",
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("WORKS - <br>" + JSON.stringify(returnhtml));
}
});
The problem lies in how you send the data to API Gateway.
Without knowing the details of your API configuration I am guessing that you have a Request Mapping setup for application/json.
jQuery will by default post your data as application/x-www-form-urlencoded but you want to send it as json.
You can do this without having to fiddle too much with the data yourself:
var requestParams = {
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
method: "POST,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
"device": "test",
"datetime": "1446757400919"
});
};
var request = $.ajax(requestParams);
The key here is JSON.stringify() and telling jQuery that the dataType is json as well as setting the contentType to application/json.

worklight adapter using restful webservice

I am using worklight adapter to implementing on restful web service. but i can not get any successful response.
This is my adapter:
function getTest(username,password) {
var path = "http://test.mybluemix.net";
var request = 'username='+username+'&'+'password='+password;
var input = {
method : 'get',
returnedContentType : 'plain',
path : path,
headers: {
"Host":"http://test.mybluemix.net"
},
body : {
contentType: 'text/xml; charset=UTF-8',
content: request.toString()
}
};
return WL.Server.invokeHttp(input);
}
this i got response for when i call the adapter..
response header is connection close and X-Backside-Transport is failed
normally i have to hit above the url its working fine http://test.mybluemix.net/?username=sssss&password=dffa
response : {"ID":"5","USERNAME":"sassad","PASSWORD":"adsa","ROLE":"abc","PHONENUMBER":"12345678"}
Several things look wrong to me.
The path variable should not point to the hostname. It's supposed to be the part afterwards:
In the adapter XML file you define the protocol, host and port values.
Then you provide the path, for example: http://myhost:8080/THE-PATH. In this case I don't think you need it since according to your working URL example there is no actual path - there are only the parameters, the request.
I'm not sure you need the host header. Try w/out it first...
Try this. Hopefully that'll work.
function getTest(username,password) {
var request = 'username='+username+'&'+'password='+password;
var input = {
method : 'get',
returnedContentType : 'plain',
path : path,
//headers: {
// "Host":"http://test.mybluemix.net"
// },
body : {
contentType: 'text/xml; charset=UTF-8',
content: request.toString()
}
};
return WL.Server.invokeHttp(input);
}

sencha touch2 Login examples

I need a cross-domain user login request instance, please help me, thank you!!
My code
Ext.data.JsonP.request({
url: 'http://25.30.2.3:8080/newvbo/applyaction!longin',
params: {
username:'13881901678',
password:'111111',
},
success: function(response, opts) {
alert('1');
},
failure: function(response, opts) {
alert('2');
}
});
My question is, I not receive the server returns the value, I wrong?
You can Try this
Ext.Ajax.request({
method:'GET',
contentType:'application/json; charset=utf-8',
dataType:'json',
url:'http://........Login',
disableCaching: false,
withCredentials: true,
useDefaultXhrHeader: false,
callbackKey: 'callback',
params: {
EmailId:Ext.getCmp('usernametwoway').getValue(),
Password:Ext.getCmp('loginpasswordtwoway').getValue(),
},
success:function(response)
{
console.log(response);
var res = response.responseText;
var jsonarr = Ext.decode(response.responseText);
console.log(jsonarr);
var myres = jsonarr[0].Result;
console.log(myres);
switch(myres)
{
case '1':
console.log("Registration response is successfully");
Ext.Viewport.setActiveItem({xtype:'passengerdetailstwoway'});
break;
case '0':
console.log("Failed");
Ext.Msg.alert("Error","Login Failed",Ext.emptyFn);
break;
Based on the responce you can Specify the Switch case..
Hi #jesse you can try for cross-domain something like this,
Ext.Ajax.request({
url: 'your_url_path',
timeout: 90000,
params: {
withCredentials: true,
useDefaultXhrHeader: false,
username:'13881901678',
password:'111111',
},
success: function(response, o) {
if(response != '') {
alert('1')
}
},
failure: function(response, o) {
alert('2')
}
})
For cross-domain you need put withCredentials: true and useDefaultXhrHeader: false.
I hope help you.
I would like to suggest you a different approach because sending login credentials as GET parameter to remote server over http is not a good idea, instead you should use POST method over HTTPS. Now you would think JSONP doesn't support POST so how can I do this, but if you are going to install your app on Phone or iPad it would do remote call from browser without using JsonP, which means you can use normal AJAX proxy to do whatever you want. Check this out:
How to use json proxy to access remote services during development
Which means this should work:
var obj = new Object();
obj.userId = username;
obj.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'https://login_url',
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : data,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
},
failure : function(response) {
}
});

passing parameters to RIA service from extjs with json end point

I am trying to communicate with RIA service from extjs using POST for getting response with following code.
var store = Ext.create('Ext.data.Store', {
model: 'RootResults',
proxy: {
type: 'ajax',
actionMethods: 'POST',
url: 'MyService.svc/JSON/GetRes',
headers: {
'Content-type': 'application/json'
},
reader: {
type: 'json',
root: 'GetResResult.RootResults',
totalProperty: 'GetResResult.TotalCount'
}
, pageParam: undefined,
startParam: undefined,
limitParam: undefined
, success: function (response) {
alert(response);
}
}
});
var operation = new Ext.data.Operation({
FId: 1,
SId: 0
});
store.load({ params: Ext.encode(operation) });
i can access it with get.
when i am trying with POST, it returning error - "405 Method Not Allowed".
what to do to make it POST enabled?
When i asked this question, i am bit confused with POST communication between extjs and RIA services.
I solved this with the help of following article
http://www.joseph-connolly.com/blog/post/WCF-RIA-Services-jQuery-and-JSON-endpoint-Part-2.aspx
For accessing WCF RIA Services from jquery or extjs, actually we need to create changeset for CUD(Create-Update-Delete) operations and All of the operations use JSON/SubmitChanges.
I believe that on the server end you need to add HasSideEffects to your method declaration ():
[Invoke(HasSideEffects = true)]
public GetPages(...)
{
}

extjs4 store addes get params in the url

i'm using extjs4 store
In xhtpp calls it shows the http://localhost/home_dir/index.php/questions/content_pie?_dc=1312366604831&hi=&page=1&start=0&limit=25
This is the store code
var content_type_store = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: BASE_URL+'questions/content_pie',
method:'POST',
params :{hi:''}
}),
reader: new Ext.data.JsonReader({
root: 'results'
}, [
'qtype',
'qval'
])
});
Even though i set the method as POST its get params appears in url
I'm using codeigniter as my framework. I disabled GET params in CI. Iwnat to send params in post. with ext2 and 3 this code worked fine..
Help me
Thanks
method:'POST' in proxy's config won't work. There is no such config option. However there are two ways to make store use POST. The simplier one - just override getMethod function:
var content_type_store = new Ext.data.Store({
proxy: {
type: 'ajax',
url: BASE_URL+'questions/content_pie',
extraParams :{hi:''},
// Here Magic comes
getMethod: function(request){ return 'POST'; }
},
reader: {
type: 'json',
root: 'results'
}
});
The second way: override proxy's actionMethods property. If you choose this way your proxy should look like this:
// ...
proxy: {
type: 'ajax',
url: BASE_URL+'questions/content_pie',
extraParams :{hi:''},
// Here Magic comes
actionMethods: {
create : 'POST',
read : 'POST',
update : 'POST',
destroy: 'POST'
}
},
// ...