Sending json array as querystring in senchatouch2 - arrays

Should we send json array or normal array as querystring in senchatouch2

in any case you can only send String in URL so if you have JSON then use Ext.JSON.encode to make it string and if you have JS Array use toString or join method to flatten the array before appending it to URL.
Since you said querystring so I suppose you and not doing POST request.
[EDIT]
Looking at your comment it seems you want to send some data to service for creation but in that case you should not send data as querystring, you should send it in message body. Following is example to send JSON data to your service:
var obj = new Object();
obj.loginEntry = new Object();
obj.loginEntry.userid = username;
obj.loginEntry.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'http://myserver:port/service/entity',
method : "POST",
headers: {
/* Important because default is
* Content-Type:application/x-www-form-urlencoded; charset=UTF-8
* which is not supported by service
*/
'Content-Type': 'application/json'
},
params : data,
success : function(response) {
},
failure : function(response) {
}
}
);
[/EDIT]

While we use POST method to send parameters in Sencha Touch2 use jsonData in Ajax Request like,
Ext.Ajax.request({
url:'',
method:'POST',
disableCaching:false,
headers: {
'Accept':'application/json',
'Content-Type':'application/json'
},
jsonData: {
FirstName:fname //{"FirstName":["Sam","paul"]}
},
success: function(response)
{
console.log(response.responseText);
},
failure: function(response)
{
console.log(response.responseText);
},
});

Related

Can't send params to Spring get method

I'm trying to make a get request with some params to a Spring get method. I'm using angular to make a call and this is my example
var apiUrl = 'api/trupci-filter';
var req = {
method: 'GET',
url: apiUrl,
headers: {
'Content-Type': "application/x-www-form-urlencoded" or "application/json"
},
data: {
klasa: "1",
promjer:"1",
duzina: "1"
}
}
console.log(req)
return $http(req)
And this is my get method in Spring:
#GetMapping("/trupci-filter")
#Timed
public ResponseEntity<List<Trupci>> getTrupciWithFilter(
#RequestParam(value = "klasa", required = false) String klasa,
#RequestParam(value = "promjer", required = false) String promjer,
#RequestParam(value = "duzina", required = false) String duzina )
The call is successful but the params are always null. I can't find any solution to this simple thing and I'm losing my mind.
Can anybody help me?
HTTP GET request can't have data element, its for request body like for HTTP POST, PUT etc. Please use params for query string parameters.
var req = {
method: 'GET',
url: apiUrl,
params: {
klasa: "1",
promjer:"1",
duzina: "1"
}
}

angular POST not working with servlet

I am trying to use angularjs POST (or even GET) to a servlet with the following:
var json = { hello: "world" }
var deffered = $q.defer();
$http({
method: "POST",
url: url,
headers: { "Content-Type" : "application/json" },
request: JSON.stringify(json)
}).then(data) {
if(data.data) {
deferred.resolve({
response : data
});
)
})
return deffered.promise;
within the servlet, simple:
String val = request.getParameter("request")
it never seems to see it
I have tried:
data: JSON.stringify({ request: json })
data: { request: json }
"request" : JSON.stringify(json)
etc
if I comment out the getParameter and just return a generic value using Gson
JsonObject json = new JsonObject();
json.addProperty("This", "works");
response.getWriter().print(new Gson().toJson(json));
that comes back fine so is there something within the angular POST I am doing wrong here? I have also tried using "GET" instead but same result.
EDIT: I would like to understand POST method and the "proper" way to get the data from the json object if getParameter is wrong please~
getParameter() returns http request parameters, you should add this params by using :
params: JSON.stringify(json)
Not with
request: JSON.stringify(json)
Take a look in params in get and params in post.

Angularjs $http.post to contact form 7 with content type application/x-www-form-urlencoded

I'm successfully sending POST request from chrome postman plug-in to contact-form-7 and I receive mail and everything.
What I can't figure out is how to send same POST request from angular.
Here's what I have in postman:
POST url: http://example.com/be/home/
REQUEST:
_wpcf7:4
_wpcf7_version:4.7
_wpcf7_locale:en_US
_wpcf7_unit_tag:wpcf7-f4-p6-o1
fname:john
email:admin#example.com
subject:subject
message:message
_wpcf7_is_ajax_call:1
HEADERS:
Content-Type:application/x-www-form-urlencoded
Accept:application/json, text/javascript, */*;q=0.01
BODY(raw):
_wpcf7=4&_wpcf7_version=4.7&_wpcf7_locale=en_US&_wpcf7_unit_tag=wpcf7-f4-p6-o1&fname=john&email=admin#example.com&subject=subject&message=message&_wpcf7_is_ajax_call=1
RESPONSE:
<textarea>{"mailSent":true,"into":"#wpcf7-f4-p6-o1","captcha":null,"message":"Thank you for your message. It has been sent."}</textarea>
Here's what I tried so far:
HomeService:
this.sendMessage = function(successCallback, errorCallback){
$http.post('/be/home', {
headers:{
'Content-Type':'application/x-www-form-urlencoded',
'Accept':'application/json, text/javascript, */*;q=0.01'
},
data:{
'_wpcf7':4,
'_wpcf7_version':4.7,
'_wpcf7_locale':'en_US',
'_wpcf7_unit_tag':'wpcf7-f4-p6-o1',
'fname':'john',
'email':'admin#example.com',
'subject':'subject',
'message':'message',
'_wpcf7_is_ajax_call':1
}
}).then(function(data){
successCallback(data);
}).catch(function(data){
errorCallback(data);
});
}
}
HomeController:
HomeService.sendMessage(function(data){
console.log(data);
}, function(data){
console.log(data);
}
In response I get the whole page, I think I'm sending the headers and data wrong, but I can't figure out how to do it.
EDIT:
{"_wpcf7":4,"_wpcf7_version":4.7,"_wpcf7_locale":"en_US","_w‌​pcf7_unit... This is how REQUEST BODY looks like(JSON) I need it to look like this (form data):
_wpcf7=4&_wpcf7_version=4.7&_wpcf7_locale=en_US&_wpcf7_unit_‌​tag=wpcf7-f4-p6-o1&f‌​name=john&email=admi‌​n%40example.com&subj‌​ect=subject&message=‌​message&_wpcf7_is_aj‌​ax_call=1
And HEADERS: Content-Type:"application/x-www-form-urlencoded"
When I edit request to look like this second example, request passes and email is sent. So question is, is it possible to post Form Data instead of JSON with $http.post?
EDIT:
SOLUTION by #georgeawg
HomeService:
this.sendMessage = function(){
var config = {
//USE serializer
transformRequest: $httpParamSerializer,
headers:{
'Content-Type':'application/x-www-form-urlencoded',
'Accept':'application/json, text/javascript, */*;q=0.01'
}
};
var data = {
'_wpcf7':4,
'_wpcf7_version':4.7,
'_wpcf7_locale':'en_US',
'_wpcf7_unit_tag':'wpcf7-f4-p6-o1',
'fname':'john',
'email':'admin#example.com',
'subject':'subject',
'message':'message',
'_wpcf7_is_ajax_call':1
};
//vvvv RETURN httpPromise
return $http.post('/be/home', data, config);
};
To POST data with content type application/x-www-form-urlencoded, the data needs to be urlencoded. Use the $httpParamSerializer service:
//this.sendMessage = function(successCallback, errorCallback){
this.sendMessage = function(){
var config = {
//USE serializer
transformRequest: $httpParamSerializer,
headers:{
'Content-Type':'application/x-www-form-urlencoded',
'Accept':'application/json, text/javascript, */*;q=0.01'
}
};
var data = {
'_wpcf7':4,
'_wpcf7_version':4.7,
'_wpcf7_locale':'en_US',
'_wpcf7_unit_tag':'wpcf7-f4-p6-o1',
'fname':'john',
'email':'admin#example.com',
'subject':'subject',
'message':'message',
'_wpcf7_is_ajax_call':1
};
//vvvv RETURN httpPromise
return $http.post('/be/home', data, config);
};
The # in the email needs to be percent encoded. The param serializer will do that properly.
Also the is no need to use success and error callbacks as the $http service already returns a promise.
See Why are Callbacks from Promise .then Methods an Anti-Pattern.
In the headers, you specify 'Content-Type':'application/x-www-form-urlencoded' while you provide value in a JSON format in the data property :
data:{
'_wpcf7':4,
'_wpcf7_version':4.7,
'_wpcf7_locale':'en_US',
'_wpcf7_unit_tag':'wpcf7-f4-p6-o1',
'fname':'john',
'email':'admin#example.com',
'subject':'subject',
'message':'message',
'_wpcf7_is_ajax_call':1
}
Either don't specify 'Content-Type':'application/x-www-form-urlencoded' in order to transmit value with the "application/json" content-type that is used by default or else if you really need to use the 'application/x-www-form-urlencoded' Content-Type, provide in the data property a string conform to what 'application/x-www-form-urlencoded' expects to, that is _wpcf7=4&_wpcf7_versio=4.7... .
Try this without adding the headers in request, see this link
HomeService:
this.sendMessage = function(successCallback, errorCallback) {
var data = {
'_wpcf7': 4,
'_wpcf7_version': 4.7,
'_wpcf7_locale': 'en_US',
'_wpcf7_unit_tag': 'wpcf7-f4-p6-o1',
'fname': 'john',
'email': 'admin#example.com',
'subject': 'subject',
'message': 'message',
'_wpcf7_is_ajax_call': 1
}
return $http.post('/be/home', $.param(data));
}
HomeController:
HomeService.sendMessage().then(function(data) {
console.log(data);
});

AngularJs Post to WebApi is always null

Angular Code:
getAuthorizationStatus: function () {
var deferred = $q.defer();
$http({
method: "POST",
url: url,
data: {
username: $scope.username,
password: $scope.password
},
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
},
My Server side code:
[HttpPost]
public int ValidateUser([FromBody]Credentials credentials)
{
try
{
string username = credentials.username;
string password = credentials.password;
//Do stuff
}
catch (Exception ex)
{
throw ex;
return -1;
}
return -1; // not valid user
}
The problem I am having is I am able to hit the Api Method but the data inside is always null. I have tried several combinations like this:
data: JSON.stringify({
"username" : "username",
"password":"mypassword"
}),
No dice.
What am I doing in wrong ?
Enclose your data in $.param()
Example :
data: $.param({ username: $scope.username,password: $scope.password })
I would instead trying to change the default and appropriate behavior of $http's POST, instead let the server read the data from the right place. Taken from MVC controller : get JSON object from HTTP body?:
[HttpPost]
public ActionResult Index(int? id)
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
InputClass input = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
input = JsonConvert.DeserializeObject<InputClass>(json)
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do stuff
}
It turns out that MVC doesn't really bind the POST body to any
particular class. Nor can you just fetch the POST body as a param of
the ActionResult (suggested in another answer). Fair enough. You need
to fetch it from the request stream yourself and process it.
Using [FromBody] beside the action input param is enough to get the data from request. Your problem is that you override the content-type in your Angular code through headers:
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //*** Remove this!
}
It must be 'application/json' in order to send json data. Just remove that headers and it should work normally.

Sending array as querystring parameter in senchatouch2

How to send Arrays as querystring parameters in Ajax request using POST methos to access a third party webservice..
Kindly provide sample code ..
While v use POST method to send parameters in SenchaTouch2 use jsonData instead of params in Ajax Request like,
Ext.Ajax.request({
url:'',
method:'POST',
disableCaching:false,
headers: {
'Accept':'application/json',
'Content-Type':'application/json'
},
**jsonData**: {
FirstName:fname //{"FirstName":["Sam","paul"]}
},
success: function(response)
{
console.log(response.responseText);
},
failure: function(response)
{
console.log(response.responseText);
}
});
This is the way I usually do it
...
params: {
array: Ext.encode(['1', '2', '3'])
},
...
Hope this helps

Resources