Dojo /JSON post request on method with multiple parameters? - javascript

This should be basics but I'm having trouble with posting multiple parameters from dojo on a rest endpoint. I have the following method on my back end exposed via resteasy.
#POST()
#Path("/updateProduct")
#Consumes(MediaType.APPLICATION_JSON)
public void updateGeneralSettings(String session,Product product) {
System.out.println("session"+session);
System.out.println("product"+product.toString);
}
This works perfectly fine just with Product as the parameter. I'm yet to figure out how to build a jason string with another parameter. Product data just binding from form and this is some additional parameter I wanted to attach with it (i.e. session).
jsonData = dojo.toJson(product)
var handler = request.post(url, {
data: jsonData,
headers: {
"Content-Type": 'application/json; charset=utf-8',
"Accept": "application/json"
}
});
Appreciate if you guys can give me some solution.

Try adding parameter names to your method signature:
public void updateGeneralSettings(#FormParam("session") String session, #FormParam("product") Product product)
and then something like:
var handler = request.post(url, {
data: {
session: session,
product: jsonData
},
headers: {
"Content-Type": 'application/json; charset=utf-8',
"Accept": "application/json"
}
});

Related

put request in angular sends empty form data

I am trying to make a put request.
The api requires an array of numbers as request parameter
$http({
'requestpath/putrequesturl',
{
categories: [categorylist]
},
{
'method': 'PUT',
'authToken': authToken,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
the data is sent as
requestpath/putrequesturl?categories=%5B5,19,12%5D
the query string parameter shows correct data, but Form Data in chrome dev tools is empty.
I tried this without content-type too, but it does not work
How can i make this request to send data as Form Data (Request body)
Edit: this is what api requires to get sent (if this is necessary):
Parameter: categories type:array
Your $http params looks a little odd. Maybe you are trying to do something like this..
$http({
method: "PUT",
uri: 'requestpath/putrequesturl',
headers: {
"Content-Type": "application/json",
"authToken": authToken // assuming this should be in the header
},
data: {
categories: [categorylist]
}
})
This is how the method put should seems
$http({
method: 'PUT',
url: uri,
headers: {"Content-Type": "application/json;charset=UTF-8"},
data: someData
});
or
$http.put(url, data, config)

Model binding a list on a complex type in ASP.NET Core

I'm having trouble with model binding in ASP.NET Core MVC. I have this endpoint, which gets hit when called from Javascript, but the postData is always null.
[HttpPost("/somepost")]
public string SomePost([FromBody] PostData postData)
{
return "Got It!";
}
public class PostData
{
public int ID { get; set; }
public string[] ListOrArray { get; set; } // Doesn't matter if this ends up a List or an Array
}
This endpoint is being hit from a $.click function:
$('img.some-image').click(function () {
array = ['sample data', 'some more'];
data = {
ID: 1,
ListOrArray: array
};
$.ajax({
type: 'POST',
url: '/somepost',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (result) {
console.log('Received: ');
console.log(result);
}
});
});
I'm guessing that the problem is model binding, but I am not sure. I've seen examples with lowercase Javascript object property names, but that didn't change anything for me.
I also have to remove [ValidateAntiForgeryToken] from the POST, but I would prefer adding it back in. I'm guessing that I would have to add the token to the GET request so that I could submit it for the POST, but I haven't figured out how to do that. I don't think that has anything to do with my problem though.
I've searched for answers and examples, but none of them have worked for me. ASP.NET Core is pretty new so there isn't much out there. I am on version 1.1.0.
You have set contentType:json but you are sending a plain object you need to send json object.
To convert your object to json object you can use JSON.stringify
$.ajax({
type: 'POST',
url: '/somepost',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (result) {
console.log('Received: ');
console.log(result);
}
});

How to manage http content-type in web application [duplicate]

I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.
I am trying to make an AJAX call to the server side, using $http from my Angular App.
For sending the parameters, I tried the following:
$http({
method: "post",
url: URL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
console.log(result);
});
This is working, but it is using jQuery as well at $.param. For removing the dependency on jQuery, I tried:
data: {username: $scope.userName, password: $scope.password}
but this seemed to fail. Then I tried params:
params: {username: $scope.userName, password: $scope.password}
but this also seemed to fail. Then I tried JSON.stringify:
data: JSON.stringify({username: $scope.userName, password: $scope.password})
I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong? I am sure, AngularJS would provide this functionality, but how?
I think you need to do is to transform your data from object not to JSON string, but to url params.
From Ben Nadel's blog.
By default, the $http service will transform the outgoing request by
serializing the data as JSON and then posting it with the content-
type, "application/json". When we want to post the value as a FORM
post, we need to change the serialization algorithm and post the data
with the content-type, "application/x-www-form-urlencoded".
Example from here.
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {username: $scope.userName, password: $scope.password}
}).then(function () {});
UPDATE
To use new services added with AngularJS V1.4, see
URL-encoding variables using only AngularJS services
URL-encoding variables using only AngularJS services
With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:
$httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)
$httpParamSerializer - a serializer used by Angular itself for GET requests
Example with $http()
$http({
url: 'some/api/endpoint',
method: 'POST',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}).then(function(response) { /* do something here */ });
See a more verbose Plunker demo
Example with $http.post()
$http.post(
'some/api/endpoint',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}
).then(function
How are $httpParamSerializerJQLike and $httpParamSerializer different
In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.
For example (ignoring percent encoding of brackets):
• Encoding an array
{sites:['google', 'Facebook']} // Object with array property
sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike
sites=google&sites=facebook // Result with $httpParamSerializer
• Encoding an object
{address: {city: 'LA', country: 'USA'}} // Object with object property
address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike
address={"city": "LA", country: "USA"} // Result with $httpParamSerializer
All of these look like overkill (or don't work)... just do this:
$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
`&password=${ encodeURIComponent(password) }` +
'&grant_type=password'
).success(function (data) {
The problem is the JSON string format, You can use a simple URL string in data:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});
Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support application/x-www-form-urlencoded, then throw it away ... hopefully AngularJS does !
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.username+'&password='+$scope.password
}).then(function(response) {
// on success
}, function(response) {
// on error
});
Works like a charm with AngularJS 1.5
People, let give u some advice:
use promises .then(success, error) when dealing with $http, forget about .sucess and .error callbacks (as they are being deprecated)
From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."
If your data model is more complex that just a username and a password, you can still do that (as suggested above)
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: json_formatted_data,
transformRequest: function(data, headers) {
return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
}
}).then(function(response) {
// on succes
}, function(response) {
// on error
});
Document for the encodeURIComponent can be found here
If it is a form try changing the header to:
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
and if it is not a form and a simple json then try this header:
headers[ "Content-type" ] = "application/json";
From the $http docs this should work..
$http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(response) {
// your code...
});
$http({
method: "POST",
url: "/server.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "name='Олег'&age='28'",
}).success(function(data, status) {
console.log(data);
console.log(status);
});
you need to post plain javascript object, nothing else
var request = $http({
method: "post",
url: "process.cfm",
transformRequest: transformRequestAsFormPost,
data: { id: 4, name: "Kim" }
});
request.success(
function( data ) {
$scope.localData = data;
}
);
if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side
Though a late answer, I found angular UrlSearchParams worked very well for me, it takes care of the encoding of parameters as well.
let params = new URLSearchParams();
params.set("abc", "def");
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http
.post(UrlUtil.getOptionSubmitUrl(parentSubcatId), params, options)
.catch();
This worked for me. I use angular for front-end and laravel php for back-end. In my project, angular web sends json data to laravel back-end.
This is my angular controller.
var angularJsApp= angular.module('angularJsApp',[]);
angularJsApp.controller('MainCtrl', function ($scope ,$http) {
$scope.userName ="Victoria";
$scope.password ="password"
$http({
method :'POST',
url:'http://api.mywebsite.com.localhost/httpTest?callback=JSON_CALLBACK',
data: { username : $scope.userName , password: $scope.password},
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
console.log('status',status);
console.log('data',status);
console.log('headers',status);
});
});
This is my php back-end laravel controller.
public function httpTest(){
if (Input::has('username')) {
$user =Input::all();
return Response::json($user)->setCallback(Input::get('callback'));
}
}
This is my laravel routing
Route::post('httpTest','HttpTestController#httpTest');
The result in browser is
status 200
data JSON_CALLBACK({"username":"Victoria","password":"password","callback":"JSON_CALLBACK"});
httpTesting.js:18 headers function (c){a||(a=sc(b));return
c?a[K(c)]||null:a}
There is chrome extension called postman. You can use to test your back-end url whether it is working or not.
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
hopefully, my answer will help you.

jQuery - AJAX Request

I am working on an app that sends a POST request to a web service. My POST request looks like this:
$.ajax({
type: 'POST', url: getEntityUrl(), cache: 'false',
contentType:'application/json',
headers: {
'api-key':'myKeyHere',
'Content-Type':'application/json'
},
data: {
firstName:'Jon',
lastName:'Smith'
},
success: function() { alert('good job'); },
error: function() { alert('oops'); }
});
When I execute this, I'm getting a 400 Bad Request. I watched the request in Fiddler. I noticed that the parameters I sent are being sent as "firstName=Jon&lastName=Smith". However, they need to be sent across as JSON like I have them defined in the data parameter. I confirmed this is the problem by modifying the request in the composer in Fiddler. What am I doing wrong?
Thanks
If you pass jQuery a plain object through the data parameter (as you do here) then it will encode the data as application/x-www-form-urlencoded.
Just setting the contentType is insufficient.
If you want to send JSON then you must encode it yourself. You can use JSON.stringify for that.
data: JSON.stringify({
firstName:'Jon',
lastName:'Smith'
}),
You need to stringify the data like following.
$.ajax({
type: 'POST',
url: getEntityUrl(),
contentType: 'application/json',
headers: {
'api-key': 'myKeyHere',
'Content-Type': 'application/json'
},
data: JSON.stringify({ firstName: 'Jon', lastName: 'Smith' }), //change here
success: function () { alert('good job'); },
error: function () { alert('oops'); }
});

How do I update the public read-write OData feed at services.odata.org?

I am currently trying to get a simple demo going of a crud app using the public OData feed at http://services.odata.org/V4/(S(jskq43fsvrxbzaf2jzhboo13))/OData/OData.svc/Products
GET-ting data works, however I am unable to update the data by clicking the button, and get a 501 (Not Implemented) error. I believe it deals with the need to enable CORS. Please see my fiddle. Thanks in advance!
var requestSettings = {
url: "http://services.odata.org/V3/(S(ettihtez1pypsghekhjamb1u))/OData/OData.svc/Products(" + key + ")",
method: "POST",
headers: {
"X-Http-Method": "PATCH",
'accept': "application/json;odata=verbose"
},
'contentType': "application/json; charset=utf-8", //content-length not required
datatype: 'json',
data: JSON.stringify(values),
success: function updateSuccess() {
deferred.resolve();
alert("successful update");
},
error: function updateError() {
deferred.reject();
alert("un-successful update");
}
};
$.ajax(requestSettings);
I have a JSFiddle here:
https://jsfiddle.net/jf713jf/ybLg1b4h/4/
Consider to use DevExpress.data.ODataStore that provides logic to access OData service.
Since you're working with fourth version of OData service, the ODataStore constructor options would like that:
new DevExpress.data.ODataStore({
url: "http://services.odata.org/V4/(S(jskq43fsvrxbzaf2jzhboo13))/OData/OData.svc/Products",
key: "ID",
keyType: "Int32",
version: 4,
// To overcome the cross-origin issue
jsonp: true
});
Hope it helps.

Categories

Resources