I am trying to achieve something simple, using play framework 2.1 (java):
Post JSON data via jquery, and retrieve it from a controller.
Could you kindly tell me where I am wrong?
It starts from a javascript call:
var object = new Object();
object.title = "Hamlet";
object.author = "Bill";
var jsonData = JSON.parse(JSON.stringify(object));
jsRoutes.controllers.Application.update().ajax({
type : 'POST',
dataType : 'json',
data : jsonData,
success : function(data) {
// I get the success
},
error : function(data) {
alert('error');
}
});
The data seems to be correctly posted:
Firebug console:
Headers:
Response Headers
Content-Length 2
Content-Type text/plain; charset=utf-8
Request Headers
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
...
Parameters
Parametersapplication/x-www-form-urlencoded
title Hamlet
author Bill
Source
title=Hamlet&Author=Bill
It routes here:
POST /update controllers.Application.update()
Here is the Application Controller:
#BodyParser.Of(BodyParser.Json.class)
public static Result update() {
JsonNode json = request().body().asJson();
if(json == null){
return badRequest("empty json"); // PROBLEM: THE JSON IS ALWAYS NULL
}
return ok("{}");
}
And the problem I get is I cannot retrieve my parameters from the request.
the request() seems empty if i print it :
DefaultRequestBody(None,None,None,None,None,None,true)
Do you see where I am wrong? How could I get the JSON right?
Thanks in advance
I had exactly the same issue. Besides the dataType, you have to set contentType as well, as the original poster suggested:
var jsonMsg = JSON.stringify(msg);
jsRoutes.controllers.Application.sendJson().ajax({
type : 'POST',
dataType : 'json',
contentType : 'application/json; charset=utf-8',
data : jsonMsg
});
This might help you this example shows how to implement ajax with play step by step
Play 2.x: How to make an AJAX request with a common button
Related
I'm trying to make a POST request with custom headers and json as string on body
Here's my code
HttpRequest request2 = HttpRequest.newBuilder()
.uri(URI.create(POSTS_API_URL))
.headers("accept", "text/plain; charset=UTF-8", "XF-Api-Key", "MYAPIKEY")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
System.out.println(request2); //result : https://******.fr/api/auth/ POST
System.out.println(request2.headers()); //result : java.net.http.HttpHeaders#8e33ff08 { {accept=[text/plain; charset=UTF-8], XF-Api-Key=[MYAPIKEY]} }
HttpResponse<String> response2 = client.send(request2, HttpResponse.BodyHandlers.ofString());
// print status code
System.out.println(response2.statusCode()); //400
// print json code
System.out.println(json); //{"login":"LunaLune","password":"***********"}
// print response body
System.out.println(response2.body()); //mandatory input missing : login, password
And my json String
String json = "{" +
"\"login\":\"LunaLune\"," +
"\"password\":\"*********\"" +
"}";
But when I print the request I get : https://*******.fr/api/auth/ POST
the POST request is empty
I googled many forums, code examples ect... but I see that my code where correct according many examples I seen.
So if someone know what is my problem ?
Thanks in advance !
You need to set "Content-Type" as "application/json" in the request header.
See: Which JSON content type do I use?
I am trying to send an array of strings to a java/spring backend solution and after trying to do it in many ways I gave up cause I always have errors (malformed request, missing body...)
I am pretty surprised cause followed many examples without success. I am sure the problem is in the jquery side cause I changed the method to GET in order to see the request as clear as possible and I saw the data is not represented as expected.
This is the function:
function duplicateSection() {
var table = document.getElementById("tbody");
var ids = [];
var i = 0;
var totalRows = table.rows.length;
for(i; i < totalRows; i++){
var checkbox = table.rows[i].cells[0].children[0];
if(checkbox.checked){
var id = table.rows[i].cells[1].children[0].value;
ids.push(id);
}
}
var jsonString = JSON.stringify(ids);
alert(jsonString);
$.ajax({
url: './duplicatesections',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: jsonString,
success: function(data) {
alert('sent');
}
});
}
When I show with alert the JSON string I get the expected result: ["1"]
When the request is sent I get this other result: http://localhost:8080/duplicatesections?[%221%22]
Why do I have this representation?: [%221%22]
As an extra information, I am using spring boot and thymeleaf in case it is relevant.
send a POST request.
$.ajax({
url: './duplicatesections',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: jsonString,
success: function(data) {
alert('sent');
}
});
I'm trying to send an array from my jsp to my Servlet via ajax POST request. My array has a few objects with many fields. If I try to send and array with 11 objects - using JSON.stringify - it works OK (the array is received on server-side), but the problem happens when I try to send an array with 12+ objects. The error is: 400 Bad Request and looking with Google Chrome Debugger, I can find this error: fluxos:(unable to decode value) where fluxos is the name of my array.
RELEVANTE PART OF CODE:
for(var i=0; i<numberOfConnections; i++) {
fluxo = criaEstruturaFluxo(i);
fluxos.push(fluxo);
}
$.ajax({
type: "POST",
url: 'Servlet?fluxos='+JSON.stringify(fluxos),
success: function (data) {
alert('success');
}
});
...
function criaEstruturaFluxo(i) {
...
...
var fluxo = {
xOrigem: xOrigem,
yOrigem: yOrigem,
xDestino: xDestino,
yDestino: yDestino,
codWorkflow: codWorkflow,
acaoAvanco: acaoAvanco,
codAtividadeOrigem: codAtividadeOrigem[1],
codAtividadeDestino: codAtividadeDestino[1],
numero: numero,
nomeAtividadeOrigem: nomeAtividadeOrigem,
nomeAtividadeDestino: nomeAtividadeDestino,
codConexao: codConexao,
tipoOrigem: tipoOrigem,
tipoDestino: tipoDestino,
xFluxoOrigem: xFluxoOrigem,
yFluxoOrigem: yFluxoOrigem,
xFluxoDestino: xFluxoDestino,
yFluxoDestino: yFluxoDestino,
deletarArquivo: deletarArquivo,
ultimaConexao: ultimaConexao,
caminhoArquivo: caminhoArquivo,
xTela: xTela,
yTela: yTela
};
return fluxo;
}
My encoded array has 8000+ characters length and because of that, I think it's exceeding the max length a POST request can handle... Is that possible or might be something on the code that I'm sending to my Servlet?
Your url is very long. In theory that shouldn't cause any problems, but there's a practical limit that depends on the server and proxies that you use. Send the data on the body of the request and not on the url.
Agree with Andres & Luiggi. Here's what your modified code would look like:
$.ajax({
url: "Servlet",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "fluxos": fluxos }),
success: function(data) {
alert("success");
}
});
I am new to jQuery and am trying to use the autocomplete widget with an ajax call to my database.
I am able to call the database, returned ArrayList of string values, and converted the response as a JSON object using org.codehaus.jackson.map.ObjectMapper (Do I need to use something else?).
When I put an altar, I can see results as pure strings with comma delimiter, but am not able to see a suggestion list with autocomplete.
Java code that returns the JSON object using org.codehaus.jackson.map.ObjectMapper:
response.setContentType("application/json");
response.setHeader("cache-control", "no-cache");
ArrayList polNo = doa.getPolicyData(ajaxForm.getPolicyNumber());
ObjectMapper mapper = new ObjectMapper();
OutputStream out = response.getOutputStream();
mapper.writeValue(out, polNo);
JavaScript code:
$( "#policyNumber" ).autocomplete({
source: function (request,response){
$.ajax({
type: "POST",
url: "/NB/AjaxSubmit.do",
dataType: "json",
data: {policyNumber: request.term},
success: function (data) {
alert(data);
}
});
},minLength: 3
});
alert data showing as : TMA412732,TMA412733,TMA412734
In above code, I have returned ArrayList of string values and was able to show in autopopulate. I have enhanced the above code to return list of person objects that has first name, last name etc. Now when user typing the firname or last name in the autopopulate , I would like to suggest First name, LastName Middle.
Could someone help to enhance this? Thanks!
success: function(data) {
response(data);//u forgot to set data on response
}
Change success function like
success: function (data) {
response(data); //u forgot to set data on response
}
I am using JQuery's post(), but my servlet doesn't see the array that I'm passing as a parameter.
My javascript looks like this:
var myArray = ['1', '2'];
$.post('action.do', {"arrayData":myArray, "mode":"insert"});
In my servlet:
System.out.println(request.getParameterMap());
which outputs:
{mode=insert}
I've also tried
$.post('action.do', {"arrayData[]":myArray, "mode":"insert"});
and
$.post('action.do', {"arrayData":$(myArray).serializeArray(), "mode":"insert"});
I had this problem. I resolved it just by adding brackets to "arrayData" parameter server-side. On client:
$.post('action.do', {arrayData:myArray, mode:"insert"});
Please, note, on the client-side arrayData parameter is without brackets.
On server:
String[] arrayData=request.getParameterValues("arrayData[]");
This worked for me!
Try to use
$.post('action.do', {"arrayData":myArray, "mode":"insert"});
and on server
String[] arrayData=request.getParameterValues("arrayData");
Here is how I pass json to my servlet, using json2.js from here. In the servlet you can then use gson, or jackson to automatically convert you json to an instance of suitable java class autonoumously.
var jsonData = $("#myform").toObject();
var strJson = JSON.stringify(jsonData);
$.ajax({
cache:false,
type: 'POST',
url: myUrl,
data:strJson,
contentType: "application/json",
success: function(data) {
//mySuccessHanlder
}
});