My framework is playframework2.2.2.
I use the jquery to send ajax json:
my javascript(client) part:
$("#newapply" ).click(function(){
var htmlrespone=$.ajax({
type : 'post',
url : ' #routes.CommonController.postdata ',
data : JSON.stringify({"userid": "111233456"}),
sucess:function(){
$("#newapply" ).html("already apply");
$("#newapply" ).prop("enable",false);
},
contentType: 'appliction/json'
});
})
my post string from my firebug is:
{"userid":"111233456"}
my server part received the post is:
def postdata = Action { request =>
val body: AnyContent = request.body
val textBody: Option[JsValue] = body.asJson //here I always get None I donot know why
textBody.map{json=>
Ok("Got:"+(json\"userid").as[String])
}.getOrElse{
BadRequest("Expecting text/plain request body")
}
}
Here I always get the BadRequest as the getOrElse statement is alway None.
I think the post should be json object or JsValue.
but why here I get None? How to get the JsValue from body?
i think, you can't simply pass the request body data in ajax data.
In ajax data,just pass the variable with value,like this
var reqData=JSON.stringify({"userid": "111233456"})
$.ajax({
type : 'post',
url : ' #routes.CommonController.postdata() ', //add proper function brackets after postdata
data : {"data",reqData},
sucess:function(){
$("#newapply" ).html("already apply");
$("#newapply" ).prop("enable",false);
}
});
(sorry, i know only java not scala)
In routes file,just add like this
controllers.CommonController.postdata(data: String ?="")
and in your controller,just do like this
public static Result postdata (String data) {
//do your stuff
}
Hope this will help.
Your application/json is misspelled. Having the field contentType: 'application/json' should be all that's needed to send json request.
I've been all day trying to make the client send AJAX requests with UTF-8 encoding in FormData() objects. I'm using Sping MVC on the server side, but that doesn't apply in this case, since:
I can POST to the server non-multipart requests, and I can capture the request and see:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
and I also can see the characters encoded OK (á, é, í, ó, ú).
If I POST using AJAX + file upload + FormData, using the following code:
var data = new FormData();
data.append('body', jq("#sp_body").val());
data.append('signature', jq("#sp_signature").val());
data.append('subject', jq("#sp_subject").val());
data.append('email', jq("#sp_email").val());
data.append("file", jq("#sp_file")[0].files[0]);
jq.ajax({
url: contextPath + "/jobs/" + job + "/sendmail",
data: data,
cache: false,
dataType: 'text',
processData: false,
contentType: false,
mimeType: "multipart/form-data",
type: 'POST',
success: function(result){
data = jq.parseJSON(result);
if (data["statusCode"] == "success") {
jq("#save_status").html("Email sent!").show().delay(5000).fadeOut(200);
} else {
jq("#save_status").html(data["errors"]).show().delay(5000).fadeOut(200);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
Then I capture the request and I see:
Content-Type: multipart/form-data; boundary=---------------------------279972256522979
But no UTF-8 in the header, and the non-latin characters are garbled.
The question is, how can I POST using FormData (since I want to POST strings and a file at the same time), having UTF-8 encoding set?
I've read UTF-8 text is garbled when form is posted as multipart/form-data but that didn't help me.
In your servlet, you have to set the encoding again:
public void extractRequest(HttpServletRequest request) throws Exception {
if (request != null) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
}
catch (FileUploadException e) {
e.printStackTrace();
}
while (itr.hasNext()) {
FileItem item = itr.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("UTF-8");
...
...
In your html:
<form id="formid" action="<yourpath>" enctype="multipart/form-data"
method="POST" accept-charset="utf-8">
And of course, if you are using a database, same thing has to be set there as well
Do let me know if this helps; otherwise we can look at other areas.
I have problem trying to upload a file via json/ajax and does not look like the file was uploaded. Only name of the file was displayed in the console output.
My html code as shown below.
<form action="/cgi-bin/upload.cgi" method="post" enctype="multipart/form-data" target="upIFrame">
<input type="file" id="uploadFileName" name="uploadFileName" size="30" >
<input type="button" id="upgradeFile" name="upgradeFile" value="Upload" onclick="ul.load()" />
<iframe id="upIFrame" name="upIFrame" src="#" style="display: none;"></iframe>
</form>
the ul.load() is calling this line below and eventually the transfer.ajax code will call
transfer.ajax({
url:'upload.cgi',
data:{filename: ul.filename},
success: success,
error: error,
async: true
});
ul.filename comes from uploadFileName
and transfer.ajax code shown below
transfer = {
ajax: function(p) {
if (p.url.indexOf('/') == -1) {
p.url = '/cgi-bin/' + p.url;
}
p.type = 'POST';
p.contentType = 'application/json';
p.dataType = 'json';
p.cache = false;
if (p.data != undefined) {
p.data = JSON.stringify(p.data);
}
$.ajax(p);
}
};
the result after viewing in Fire Fox is
JSON
filename "file.tgz"
Source
{"filename":"file.tgz"}
Could some tell me what I did wrong or what I missed?
TIA
I modified the code to the following...
var fd = new FormData();
fd.append("filename",ul.filename);
$.ajax({
url: "/cgi-bin/test.cgi",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
beforeSend : function(xhr){
xhr.setRequestHeader('Content-Disposition', 'form-data; name=\"uploadFileName\"; filename=\"' + ul.filename + '\"');
},
});
and the Request Headers in Fire Fox are as
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Disposition form-data; name="uploadFileName"; filename="test.tgz"
Content-Length 157
Content-Type multipart/form-data; boundary=---------------------------20025277823050
X-Requested-With XMLHttpRequest
but the "Post" display the following
Source
-----------------------------20025277823050 Content-Disposition: form-data; name="filename"
test.tgz -----------------------------20025277823050--
How would I include filename="test.tgz"? what's missing?
TIA
Can you try this,
var fd = new FormData();
fd.append("filename",ul.filename);`enter code here`
$.ajax({
url: "/cgi-bin/test.cgi",
type: "POST",
data: fd,
processData: false,
contentType: false,
beforeSend : function(xhr){
xhr.setRequestHeader('Content-Disposition', 'form-data; name=\"' + ul.filename + '\"; filename=\"' + ul.filename + '\"');
}
});
I think name attribute should be as the file name.
Thanks :).
My question is when I use jQuery ajax get, I am getting data at response body however it doesn't pass into success function. How can I make it work?
I am making an ajax put but it doesn't work at ie9 (works on other browsers) so I changed it like that just for test:
$.ajax({
async : false,
type: 'PUT',
contentType: 'application/json',
url:updateUrl + "?_" + new Date().getTime(),
data: JSON.stringify(model),
cache: false,
dataType: "json",
dataFilter: function(data) {
var resp = eval('(' + data + ')');
return resp;
},
success: function(data, status, xhr) {
alert("success> " + data.property);
alert(typeof data);
r = resultResponse(data);
},
error: function(data, status, xhr) {
alert("error> " + data.responseText);
try {
r = error($.parseJSON(data.responseText));
} catch (err) {
//Handle error
}
}
});
data is alerting as undefined. My put data is sending correctly, my server side works well and send response to client however I get undefined instead of data. After some tests I realized the problem:
When I capture network communication packets at ie 9 response body is what I want. However success function can not handle it. If needed, I can give more information about my server(I could make it work when I write the data to response instead of using jackson json mapper at Java - it was working and the only difference was that was not included ta working version at response headers:
Key Value
Content-Type application/json;charset=UTF8 )
I think that the problem can be handle at client side, I think not with server side.
Any ideas?
EDIT: I tried that style:
$.ajax({url: "/url",
dataType: "text",
success: function(text) {
json = eval("(" + text + ")");
// do something with JSON
}
});
However response header is still:
Key Value
Content-Type application/json;charset=UTF8
The problem was wrong charset. It was UTF( instead of UTF-8).
In the code below, the AngularJS $http method calls the URL, and submits the xsrf object as a "Request Payload" (as described in the Chrome debugger network tab). The jQuery $.ajax method does the same call, but submits xsrf as "Form Data".
How can I make AngularJS submit xsrf as form data instead of a request payload?
var url = 'http://somewhere.com/';
var xsrf = {fkey: 'xsrf key'};
$http({
method: 'POST',
url: url,
data: xsrf
}).success(function () {});
$.ajax({
type: 'POST',
url: url,
data: xsrf,
dataType: 'json',
success: function() {}
});
The following line needs to be added to the $http object that is passed:
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
And the data passed should be converted to a URL-encoded string:
> $.param({fkey: "key"})
'fkey=key'
So you have something like:
$http({
method: 'POST',
url: url,
data: $.param({fkey: "key"}),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
From: https://groups.google.com/forum/#!msg/angular/5nAedJ1LyO0/4Vj_72EZcDsJ
UPDATE
To use new services added with AngularJS V1.4, see
URL-encoding variables using only AngularJS services
If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301
$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: xsrf
}).success(function () {});
I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:
.config(['$httpProvider', function ($httpProvider) {
// Intercept POST requests, convert to standard form encoding
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
var key, result = [];
if (typeof data === "string")
return data;
for (key in data) {
if (data.hasOwnProperty(key))
result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
return result.join("&");
});
}]);
As of AngularJS v1.4.0, there is a built-in $httpParamSerializer service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.
It can be used like this:
$http.post('http://example.com', $httpParamSerializer(formDataObj)).
success(function(data){/* response status 200-299 */}).
error(function(data){/* response status 400-999 */});
Remember that for a correct form post, the Content-Type header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
To do this only for the current post, the headers property of the request-object needs to be modified:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializer(formDataObj)
};
$http(req);
You can define the behavior globally:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
So you don't have to redefine it every time:
$http.post("/handle/post", {
foo: "FOO",
bar: "BAR"
}).success(function (data, status, headers, config) {
// TODO
}).error(function (data, status, headers, config) {
// TODO
});
As a workaround you can simply make the code receiving the POST respond to application/json data. For PHP I added the code below, allowing me to POST to it in either form-encoded or JSON.
//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
$_POST = json_decode(file_get_contents('php://input'),true);
//now continue to reference $_POST vars as usual
These answers look like insane overkill, sometimes, simple is just better:
$http.post(loginUrl, "userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password"
).success(function (data) {
//...
You can try with below solution
$http({
method: 'POST',
url: url-post,
data: data-post-object-json,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for (var key in obj) {
if (obj[key] instanceof Array) {
for(var idx in obj[key]){
var subObj = obj[key][idx];
for(var subKey in subObj){
str.push(encodeURIComponent(key) + "[" + idx + "][" + encodeURIComponent(subKey) + "]=" + encodeURIComponent(subObj[subKey]));
}
}
}
else {
str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
}
}
return str.join("&");
}
}).success(function(response) {
/* Do something */
});
Create an adapter service for post:
services.service('Http', function ($http) {
var self = this
this.post = function (url, data) {
return $http({
method: 'POST',
url: url,
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
}
})
Use it in your controllers or whatever:
ctrls.controller('PersonCtrl', function (Http /* our service */) {
var self = this
self.user = {name: "Ozgur", eMail: null}
self.register = function () {
Http.post('/user/register', self.user).then(function (r) {
//response
console.log(r)
})
}
})
There is a really nice tutorial that goes over this and other related stuff - Submitting AJAX Forms: The AngularJS Way.
Basically, you need to set the header of the POST request to indicate that you are sending form data as a URL encoded string, and set the data to be sent the same format
$http({
method : 'POST',
url : 'url',
data : $.param(xsrf), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
});
Note that jQuery's param() helper function is used here for serialising the data into a string, but you can do this manually as well if not using jQuery.
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
Please checkout!
https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
For Symfony2 users:
If you don't want to change anything in your javascript for this to work you can do these modifications in you symfony app:
Create a class that extends Symfony\Component\HttpFoundation\Request class:
<?php
namespace Acme\Test\MyRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
class MyRequest extends Request{
/**
* Override and extend the createFromGlobals function.
*
*
*
* #return Request A new request
*
* #api
*/
public static function createFromGlobals()
{
// Get what we would get from the parent
$request = parent::createFromGlobals();
// Add the handling for 'application/json' content type.
if(0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/json')){
// The json is in the content
$cont = $request->getContent();
$json = json_decode($cont);
// ParameterBag must be an Array.
if(is_object($json)) {
$json = (array) $json;
}
$request->request = new ParameterBag($json);
}
return $request;
}
}
Now use you class in app_dev.php (or any index file that you use)
// web/app_dev.php
$kernel = new AppKernel('dev', true);
// $kernel->loadClassCache();
$request = ForumBundleRequest::createFromGlobals();
// use your class instead
// $request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Just set Content-Type is not enough, url encode form data before send.
$http.post(url, jQuery.param(data))
I'm currently using the following solution I found in the AngularJS google group.
$http
.post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(data)), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data) {
$scope.data = data;
});
Note that if you're using PHP, you'll need to use something like Symfony 2 HTTP component's Request::createFromGlobals() to read this, as $_POST won't automatically loaded with it.
AngularJS is doing it right as it doing the following content-type inside the http-request header:
Content-Type: application/json
If you are going with php like me, or even with Symfony2 you can simply extend your server compatibility for the json standard like described here: http://silex.sensiolabs.org/doc/cookbook/json_request_body.html
The Symfony2 way (e.g. inside your DefaultController):
$request = $this->getRequest();
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
var_dump($request->request->all());
The advantage would be, that you dont need to use jQuery param and you could use AngularJS its native way of doing such requests.
Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer
var res = $resource(serverUrl + 'Token', { }, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
}, function (error) {
});
In your app config -
$httpProvider.defaults.transformRequest = function (data) {
if (data === undefined)
return data;
var clonedData = $.extend(true, {}, data);
for (var property in clonedData)
if (property.substr(0, 1) == '$')
delete clonedData[property];
return $.param(clonedData);
};
With your resource request -
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
This isn't a direct answer, but rather a slightly different design direction:
Do not post the data as a form, but as a JSON object to be directly mapped to server-side object, or use REST style path variable
Now I know neither option might be suitable in your case since you're trying to pass a XSRF key. Mapping it into a path variable like this is a terrible design:
http://www.someexample.com/xsrf/{xsrfKey}
Because by nature you would want to pass xsrf key to other path too, /login, /book-appointment etc. and you don't want to mess your pretty URL
Interestingly adding it as an object field isn't appropriate either, because now on each of json object you pass to server you have to add the field
{
appointmentId : 23,
name : 'Joe Citizen',
xsrf : '...'
}
You certainly don't want to add another field on your server-side class which does not have a direct semantic association with the domain object.
In my opinion the best way to pass your xsrf key is via a HTTP header. Many xsrf protection server-side web framework library support this. For example in Java Spring, you can pass it using X-CSRF-TOKEN header.
Angular's excellent capability of binding JS object to UI object means we can get rid of the practice of posting form all together, and post JSON instead. JSON can be easily de-serialized into server-side object and support complex data structures such as map, arrays, nested objects, etc.
How do you post array in a form payload? Maybe like this:
shopLocation=downtown&daysOpen=Monday&daysOpen=Tuesday&daysOpen=Wednesday
or this:
shopLocation=downtwon&daysOpen=Monday,Tuesday,Wednesday
Both are poor design..
This is what I am doing for my need, Where I need to send the login data to API as form data and the Javascript Object(userData) is getting converted automatically to URL encoded data
var deferred = $q.defer();
$http({
method: 'POST',
url: apiserver + '/authenticate',
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: userData
}).success(function (response) {
//logics
deferred.resolve(response);
}).error(function (err, status) {
deferred.reject(err);
});
This how my Userdata is
var userData = {
grant_type: 'password',
username: loginData.userName,
password: loginData.password
}
The only thin you have to change is to use property "params" rather than "data" when you create your $http object:
$http({
method: 'POST',
url: serviceUrl + '/ClientUpdate',
params: { LangUserId: userId, clientJSON: clients[i] },
})
In the example above clients[i] is just JSON object (not serialized in any way). If you use "params" rather than "data" angular will serialize the object for you using $httpParamSerializer: https://docs.angularjs.org/api/ng/service/$httpParamSerializer
Use AngularJS $http service and use its post method or configure $http function.