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'].
Related
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');
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');
}
});
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
How can I pass a var from javascript to a servlet. Yes I know you can use getParameter on the servlet side, but I first need to do some javascript stuff then from there it need to pass that new variable to servlet.
See my Javascript example:
function openBrWindowAndSubmit() {
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue); //returns empty
document.forms[0].submit();
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue); //works
}
As you can see in above example the first "alert" block returns empty, but the second one returns the correct encoded value because the document.forms[0].submit is already called. So is there a way I can get the second variable "textBodyValue" (which is outside of document.forms[0].submit) to the servlet? I'm calling this at the servlet side:
String test = req.getParameter("textBody");
Here's the JSP inside a form tag which calls the function on click:
<textarea id="textBody" name="textBody"></textarea>
<input type="button" onClick="openBrWindowAndSubmit();" value="Click Here to Preview Email">
Is there any workaround to this problem?
I've been trying to change the javascript function to:
function openBrWindowAndSubmit() { //v2.0
document.forms[0].target = "_blank";
document.getElementById("action").value = "view_template";
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue);
document.forms[0].submit();
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue);
$.ajax({
url: 'http://localhost:8080/restricted/comm/Email',
data: textBodyValue,
// processData: false,
// contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
Can this work? i'm getting an undefined error when reaching the $ajax tag?
As an idea. Dont know if its correct ;) but you can check it at the jQuery api page.
$('#idOfTheForm').on('submit', function(e){
e.preventDefault();
data = { key : val , key2 : val2 };
$.ajax({
type: "post",
data: data,
url : "",
success : function(response){
console.log("return code was 200");
},
error : function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
return false;
}
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 have two ajax calls in my jsp code which go to servlet. In first call, I am setting a value in the session and in another call, I am retrieving the same value from the session. Now this value goes as response of the ajax call(2nd ajax call). My problem is:-
This value contains "\n"(eg-("ABC \n def\n geh \n xyz")) . When I store this value in a js variable and try to access it, it takes "\n" as string only. It is not recognising it as newline
ajax calls in jsp:-
$.ajax({
type : "POST",
url : "ConfiguratorStatusReportServlet?method=datagrid",
data : finaldata,
datatype : "JSON",
async : false,
success : function(msg) {
$('#contentDiv').show();
fillDataGrid(msg);
}
});
$.ajax({
type : "POST",
url : "ConfiguratorStatusReportServlet?method=chart",
data : finaldata,
datatype : "JSON",
async : false,
success : function(msg) {
fillDataChartData(msg);
}
});
code in servlet:-
HttpSession session = request.getSession();
String method = request.getParameter("method");
if(method.equalsIgnoreCase("datagrid"))
{
JSONArray listjson = CSR.firstcalledMethod();
String chartformat = CSR.callingMethod2();
System.out.println("chartformat in servlet = "+chartformat);
String result = listjson.toString();
String checkDataExists = (String) (session.getAttribute("chartformat") == null ? "Invalid" : session.getAttribute("chartformat"));
if(!checkDataExists.equalsIgnoreCase("Invalid"))
{
session.removeAttribute("chartformat");
}
session.setAttribute("chartformat", chartformat);
out.write(result);
}
else
{
String chartResult = (String) session.getAttribute("chartformat");
session.removeAttribute("chartformat");
out.write(chartResult);
}
now in the same jsp which contains the ajax calls shown above I am trying to access the variable as :-
function fillDataChartData(dataVAR) {
var chartdata = dataVAR;
alert("chartdata = "+chartdata);
}
Suppose the response in ajax contains data "APAC-OTHER,0.05 \n FCS,99.95"(i.e. dataVAR = "ABC \n DEF \n GHI" ). Now, when I am trying to alert it in the function fillDataChartData(dataVAR), it shows "APAC-OTHER,0.05 \n FCS,99.95" in alert but I want it like APAC-OTHER,0.05
FCS,99.95
How should I do that?? Please help...
It's strange. May be there are some hidden chars in your response? Anyway, you can try to replace linebreaks by br tags:
function fillDataChartData(dataVAR) {
var chartdata = dataVAR.replace(/\\n/gm, '<br>');
alert("chartdata = "+chartdata);
}