Is it not possible to send an array with GET method? - arrays

On the server side I have a method that accepts an array of integers and returns a Json object:
public JsonResult GetCorrespondingOfficers(int[] categories){
//use `categories`
return Json(model,JsonRequestBehavior.AllowGet);
}
And I have the following script on the client:
var categories=[1,2,3];
$.ajax({
url: url,
type: 'GET',
data: { categories: categories },
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
success: function (data) { alert('Success');},
async: false
});
When I run the above code I get null for the parameter categories on the server side. If I change the method from GET to POST, then it works. Does it mean that I can't send an array or any Json data with GET request? If not, then what's the problem with my code?

You can send array as a string:
...
data: { categories: JSON.stringify(categories) },
...

GET request does not have message body, so you can't use GET with contentType: 'application/json; charset=UTF-8'. When you use json in GET request, browser breaks your json and append each josn key value to the url(even if you use JSON.stringify method). Therefore for using json and REST you need to use POST method.

Related

Strange behaviour of response when it isn't json in angularjs get

I have problem with error in angularjs:
Error: [$http:baddata] Data must be a valid JSON object. Received: 'test string test string' Parse error: "{}"
So if I understand it correctly, the response from the server hasn't good JSON format. Let's say that I can't change it on the server side and I try to repair it on the frontend.
So I try to use transformResponse:
function testFunc() {
return $http.get('url', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
transformResponse: function(data)
return {'status': data}
}
})
}
And then, ok, I haven't errors and everything looks fine but I expected in response something like that: {"status": "test string test string"}
But instead, I have html code from whole my site ({"status": '<HTML>....'}) Why data isn't this string which was when it was the error? How can I deal with it?

Pass Data List from angularjs to webservice?

I'm working on app in ionic 1 platform using angularjs, in which I want to Pass List of object to Web-service, How can I do it?
I have tried doing this but was not able to send any Data..
Here is my code and how to pass list of object in data: $scope.AddNew
$http({ url: $rootScope.HostName + '/bulk', dataType: 'json', method: 'POST', contentType: "application/json; charset=utf-8", data: $scope.AddNew, headers: { 'content-type': 'application/json' } }).success(function (response) { alert("Success"); }).error(function (error) { });
If there is another approach or way to do it then please do help
Thanks in advance.
Assuming your $http call is in the controller where you can access $scope.
The way you had passed is correct, but at the server side you should accept your request body as an Array of objects.
If your server side is java spring app,
You would design your method with #RequestBody YourClass[] objs
I think your code is correct, just so it is simple and readable I would suggest this format:
$http.post($rootScope + '/bulk', $scope.AddNew).then(function(response) {
alert("Success");
}, function(error) {
})
The promise structure in AngularJS has since been updated. In regard to your question, the code should work fine if you can access AddNew through your $scope. Make sure you are handling your requests properly in the backend. Try logging for checking if data is sent and received.

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.

How to retrieve json data from a post request in Pyramid?

In Pyramid:
class ProjectorViews(Layouts):
def __init__(self, request):
self.request = request
#view_config(renderer="json", name="updates.json", request_method="POST")
def updates_view(self):
print self.request.params
JS:
$(function() {
function get_updates () {
data = JSON.stringify({'a':1});
$.post('/updates.json', data, function(res) {
});
}, 'json').done(function() {
});
}
get_updates();
});
The console shows self.request.params returns NestedMultiDict([('{"a":1}', u'')])
How do I get the keys and values in the NestedMultiDict object?
If I do self.request.params.getall("a"), it reports
KeyError: "Key not found: 'a'"
And if I do self.request.json_body, it reports
ValueError: No JSON object could be decoded
$.post() always sends data with application/x-www-form-urlencoded content type. Use $.ajax() to send the data with correct content type:
$.ajax({
url: url,
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(...);
On the Pyramid side request.json_body is the correct way to access... well, JSON body of the request.

backbone.js error when using fetch but not $.ajax()

I am having some trouble fetching a collection. I'm using the console's network inspector to see if I can figure out what's wrong and the only thing I see is the format of the Request Payload.
When making a .fetch() the Request Payload is being sent in this format:
query=this+is+my+query
This returns a 400 Bad Request status from my server. I have tested using:
$.ajax({
contentType: 'application/json',
async : false,
type:'POST',
url: '/search',
data: JSON.stringify({"query":"this is my query"}),
dataType: 'json',
success: function(data) {
alert('yup');
},
error: function(data) {
alert('nope');
}});
which returns my data as expected. In this case the Request Payload is in this format:
{"query":"enterprise search is gonna rock","scope":null}
I've tried passing in headers with my fetch:
my_results.fetch({data:{"query":"this is my query"}, type: 'POST', dataType: 'json', contentType: 'application/json'});
Here is what my Model and Collection look like:
EnterpriseSearch.Result = Backbone.Model.extend();
EnterpriseSearch.Results = Backbone.Collection.extend({
model: EnterpriseSearch.Result,
url: "/search"
});
Any help would be appreciated.
Try using data: JSON.stringify({"query":"this is my query"}) in your fetch options, just like you do when using $.ajax. jQuery will default to application/x-www-form-urlencoded for form data.

Resources