jquery error sending array of Strings to Spring application - java

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

Related

Parse files in FileList object

I am using FormData to upload multiple files in my grails project.The files needs to be uploaded via Ajax. I have used following code for ajax upload. But in controller, I get the params as [object FileList]. How do I get files from this object. Is there any way to change this object to multipart?
jQuery('#file-save').click(function() {
if (jQuery('#form input[type="file"]')) {
var form = jQuery("#form").find('input[type="file"]');
var picData = new FormData();
picData.append('userFiles', form.get(0).files);
picData.append('userId', '$usrId');
jQuery.ajax({
url: '/file/upload',
type: 'post',
dataType:'json',
data: picData,
enctype: "multipart/form-data",
contentType: false,
processData: false,
success: function(data) {
console.log("success");
}
});
}
});
The controller code is:
def upload(){
def userId = params.userId
def inputFile = params.userFiles
println(inputFile)
inputFile.each{i,j->
println(i)
println(j)
}
}
When I debug, I get params.userFiles : "[object FileList]". Any insights would be appreciated.
You most likely need to loop through the files client side, adding the same key for each one
var picData = new FormData();
// loop through form.get(0).files
picData.append('userFiles', file);
// end loop
picData.append('userId', '$usrId');

Data get from ajax null in jsp

I am able to get the data from ajax using system.out.println. However, I am unable to pass the data to servlet. It shows null always.
Here is my jQuery:
function expressCheck(number) {
var Self=[];
for(i=1;i<=<%=itemCodeList.size()%>;i++) Self[i-1] = document.getElementById("qtyGuestNumber_" + i).value;
$.ajax({
url: "ViewCategories.jsp",
data: {"expressData" : Self[number-1]}
});
};

Posting two textbox values through ajax

I have some problem to post 2 items namely 'content', 'content1'. 'content' is successfully posted. But 'content1' is showing as undefined index. I have tried the below code. The lines containing 'content1' is made as comments line before posting here. Please indicate my mistakes.
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
//var textcontent1 = $("#content1").val();
var dataString = 'content='+ textcontent;
//var dataString1 = 'content1='+ textcontent1;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
//$("#content1").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
// data1: dataString1,//dataString1,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
//document.getElementById('content1').value='';
$("#flash").hide();
$("#content").focus();
//$("#content1").focus();
}
});
}
return false;
});
});
Oof - you should really indent your code!
That said - in your current code, you have the following lines commented out:
//var textcontent1 = $("#content1").val();
//var dataString1 = 'content1='+ textcontent1;
Which, yeah, those things aren't being set.
Uncomment those, and then pass the data as an object, like so:
$.ajax({
type: "POST",
url: "action.php",
data: {
'dataString' : dataString,
'dataString1' : dataString1,
},
cache: true,
// etc.
action.php will then receive those two strings as $_POST['dataString'] and $_POST['dataString1'].

String exceeding ajax POST length limit

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

Play Framework 2.1 Cannot handle JSON POST request from controller

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

Categories