Sending array as querystring parameter in senchatouch2 - arrays

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

Related

Making a $http.put with query param, path param and body

I am trying to call a API service something like url/1?param1=&param2=
it also expects a body(request payload) using $http.put.
Can anyone tell me how to do it in a efficient way?
Just don't use param: use data: in your config object.
You can pass both parameters (in the query string) and a request body like this
$http({
url: "url",
method: "put",
params: {
param1: value1,
param2: value2
}
data: JSON.stringify(objectContainingBody)
}).then(.....)
You could do something like this :
$http.put('url/path', payload, { params: { param1: 1, param2: 2 } }).then(
function(response) {
// access data with response.data
},
function(error) {
// do something with the error
}
);
If you need to convert your payload to json : angular.toJson(payload).
You can look at AngularJS $http.put for reference.

Angular $resource POSTing entire object, not just properties passed to it

I'm using Angular's $resource to interface with an API, and creating custom methods on that resource. One of these methods is a POST, and when I attempt to use it, it's sending the entire resource, not just the properties I'm attempting to post to the API. I don't think this is the intended behavior of the $resource service, but then, I might be missing something.
Here's the code:
The service:
angular.module('adminApp')
.factory('Framework', function($resource) {
return $resource('/api/frameworks/:id', {id: '#id'}, {
'update': {
method: 'PUT'
},
'getRequiredLicenses': {
method: 'GET',
url: '/api/frameworks/:id/required_licenses',
isArray: true
},
'addRequiredLicenses': {
method: 'POST',
url: '/api/frameworks/:id/required_licenses'
},
'removeRequiredLicense': {
method: 'DELETE',
url: '/api/frameworks/:id/required_licenses/:license_id'
}
});
});
Where I'm calling it:
scope.addLicensesToFramework = function() {
scope.framework.$addRequiredLicenses(null, {
required_licenses: Object.keys(scope.selectedLicenses) // returns an array of ints
});
}
(Note that this is in a directive. scope.framework is the instance of the framework resource)
When this request is sent, here's what's being included in the payload:
My intention is to only pass {'required_licenses': [12345,1236]} in the payload, and I can't seem to figure out why it's sending the entire resource as the body. (It's, in fact, not sending this at all, only the original resource)
Any insight would be really helpful, thanks!
Try calling it like this:
scope.addLicensesToFramework = function() {
scope.framework.$addRequiredLicenses({
required_licenses: Object.keys(scope.selectedLicenses),
id: 1234
}, function(resp){ console.log(resp) });
}
Also notice that I included the id in the parameters object.. you'll probably need that.

Building one object with only one $resource

I'm building a fullrest app with $resources, I read about It but I didn't find any answer.
return $resource('/rings', {}, {
getRings: {
method: 'GET',
isArray: true
},
patchRing: {
method: 'PATCH',
params: {
slug: '#slug'
}
}
}
Get Rings is doing ok, but How can I "patchRing"? I mean I want to PATCH for endpoint: /rings/:slug Is this possible? or Do I need another $resource for that (like next one)?
return $resource('/rings/:slug', { slug: '#slug'}, { [...]
EDIT: I don't want the "PATCH" like this /rings?slug=lorem just /rings/lorem
EDIT 2: My point is only the endpoint construction... because $resource is requesting to /rings?slug=lorem instead of build request like /rings/lorem
Try this in your config
$resourceProvider.defaults.stripTrailingSlashes = true;
This will not end as /
Try putting the param in the $resource definition instead of the PATCH method:
var Ring = $resource('/rings/:slug', {slug: '#slug'}, {
getRings: {
method: 'GET',
isArray: true
},
patchRing: {
method: 'PATCH',
}
});
ring = Ring.patch({slug: 'lorem'}, function() { ... });
If the slug parameter is not passed, then it is not added to the HTTP path.

Posting to a REST interface

need to define the name as ID in the URL and need to post an object containing data.
$scope.dvModel.naam is the name that acts as the ID.
filteredObject is the object containing the data, obviously.
This is how I call the service, seems ok according to some examples.
saveDVservice.query($scope.dvModel.naam, filteredObject);
This is the actual service.
.factory('saveDVservice', ['$resource', 'CONSTANTS', function($resource, CONSTANTS) {
'use strict';
return $resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});
}]);
This is what I see in my network tab at Query String Parameters:
0:A
1:D
10:n
11:h
12:i
13:l
14:f
15:e
2:A
3:C
4:
5:P
6:a
7:n
8:n
9:e
Which is the name, but looks like an array.
Request Payload contains the actual object in correct order.
Can one give me some guidance on how to handle this?
As I understand, you want to put $scope.dvModel.naam into URL and you want filteredObject to be a request payload. Then you need an object that contains everything that's in filteredObject and additionaly under the key name a value equal to $scope.dvModel.naam.
Also, the definition of your resource probably should change - in second argument $resource requires you to tell it the way of extracting URL data from given object:
$resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {name: '#name'}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});
Unfortunately, $resource isn't the best $http wrapper to use when your payload data is separated from URL data. Maybe it would be better to wrap the filteredObject data in payload in some other object? Then your $resource object would be much nicer, like {name: ..., data: {"0": "A", "1": "D", ...}}
Since default action for query is {method: 'GET', isArray: true}, I'd leave that be and use another default, save instead. That should work out-of-the-box.
app.factory('DVService', function ($resource) {
return $resource(CONSTANTS.REST_BASE_URL + '/dv', {name: '#name'}, {});
});
.
app.controller('MainCtrl', function ($scope, DVService) {
var postData = {
name: 'name',
fooProp: 'foo',
barProp: 'bar'
};
// save/post
DVservice.save({dv: postData}).$promise.then(function (response) {
console.log(response);
});
//query/get
DVService.query({name: 'name'}).$promise.then(function (response) {
console.log(response);
});
});

Sending json array as querystring in senchatouch2

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);
},
});

Resources