Passing javascript variable to servlet [duplicate] - java

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

Related

How to call an Action class in Struts 2 by AJAX with parameter [duplicate]

This question already has an answer here:
How to get json object using its key value in Struts?
(1 answer)
Closed 5 years ago.
I am trying to call an action class by AJAX with a parameter, but I can't find the right way.
I am using the following syntax from struts 2, without AJAX :
<s:url action="painel.visualizarErro.action" namespace="/errosView.jsp" var="id" />
window.location = '<s:property value="id" />?jobId=' + jobId;
The problem is I cannot pass <s:property value="id" />?jobId=' + jobId by AJAX
$.ajax(contextPath,{
type:'POST',
data:{ 'actionToPerform': methodName,
'param1': param1,
'param2': param2
},
success: function(response){
},
error : function(response){
}
});

Jquery cannot get latest value for session in my jsp page

I am using jquery ajax to send my request from client to server. I modified my codes according to #Samuel J Mathew suggestion.
$('#create_kb_btn').click(function (e) {
e.preventDefault();
$.ajax({
url: 'create',
type: "POST",
data: $('#create_kb_form').serialize(),
success: function (data) {
$('#query_form').removeClass('hidden');
$('#query_res').removeClass('hidden');
<%
Gson gson = new Gson();
String probs = gson.toJson(request.getSession().getAttribute("probs"));
String years = gson.toJson(request.getSession().getAttribute("years"));
%>
var years = JSON.parse("<%=years%>");
var probs = JSON.parse("<%=probs%>");
if (years == null || probs == null) {
alert('null');
}
updatePlot(years, probs);
document.getElementById('query_div').scrollIntoView();
},
error: function(xhr, status, error){
alert(error);
}
});
})
I'm creating a session in my create method as follows
req.getSession().setAttribute("probs", probs);
req.getSession().setAttribute("years", ec.getYears());
But somehow I always get null for years and probs. However, when I refresh the page manually, I can get the value. can anyone tell me what I'm doing wrong?
Problem Analysis :-
Based on my primary analysis on the code I found following issues in your code
On Page loading
<%
Gson gson = new Gson();
String probs = gson.toJson(request.getSession().getAttribute("probs"));
String years = gson.toJson(request.getSession().getAttribute("years"));
%>
The values of probs and years will be null because you haven't created session at all and you are trying to create session on create_kb_form form submission.
Since you are using ajax post your page will not reloaded, so the values of
var years = JSON.parse("<%=years%>");
var probs = JSON.parse("<%=probs%>");
will always be null.
This is the reason why when you refresh the page you will find that it is working fine, because at that time you have session and all the values are populated correctly.
Solution:-
The solution for above problem is as follows
You need to create a ajax success handler method where you need to return the values of probs and years from the create method.
and move
var years = JSON.parse(data).years;
var probs = JSON.parse(data).probs;
if (years == null || probs == null) {
alert('null');
}
updatePlot(years, probs);
In short your ajax function look something like this
$('#create_kb_btn').click(function (e) {
e.preventDefault();
$.ajax({
url: 'create',
type: "POST",
data: $('#create_kb_form').serialize(),
success: function (data) {
$('#query_form').removeClass('hidden');
$('#query_res').removeClass('hidden');
var years = data.years;
var probs = data.probs;
if (years == null || probs == null) {
alert('null');
}
updatePlot(years, probs);
document.getElementById('query_div').scrollIntoView();
},
error: function(xhr, status, error){
alert(error);
}
});
})
and you need to move
<%
Gson gson = new Gson();
String probs = gson.toJson(request.getSession().getAttribute("probs"));
String years = gson.toJson(request.getSession().getAttribute("years"));
//Do json encode here and send as response here
%>
to your create method.
inside ajax success handler moreover you need consider the case when already session.

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

Passing name from input to servlet

I have an input:
Now this is one input from a div with several different inputs, there is a button called add exp which generates a new div with those inputs by calling href="#" and then jquery does the rest, only the name changes to for example institutionName0, institutionName1 etc so the fields get distinct. In my servlet I want to be able to get the actual input name like institutionName0 so I can check how much of the same fields are generated and that I can put in different values in those different fields.
You can send your form values to Servlet as a jSon object using ajax.
//Example
function onSubmit(divName){
document.forms["formName"]["formName_currentAction"].value = divName;
var theForm = $("form[name=formName]");
var params = theForm.serialize();
$.ajax({
type:"POST",
url:actionURL,
cache: false,
data:params,
success:function(data, textStatus, XMLHttpRequest){
//do something here
},
error:function(XMLHttpRequest, textStatus, errorThrown){
}
});

Passing selected check boxes using jQuery servlet [duplicate]

This question already has answers here:
How to send request parameter array to servlet using jQuery $.ajax?
(4 answers)
Closed 6 years ago.
How can I pass selected checkbox values to another servlet (not below one) using jQuery post method?
This is my servlet code for generationg check boxes on the html page I am using json
for(int i=0;i<roles.size();i++){
JSONObject msg = new JSONObject();
msg.put("selector", "#roles");
//<input type=radio name="radio" value="<%=bean.getSno()%>"></td>
msg.put("msg",
"<input type=checkbox id="+'"'+"checkedroles"+'"'+"name="+'"'+"checkedroles"+'"'
+"value="+roles.get(i)+">"+roles.get(i)+"<br>");
messages.put(msg);
}
this is the jquercode
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function(){
//global vars
var UserName = $("#UserName"); //user name field
var FirstName = $("#FirstName"); //first name
var LastName=$("#LastName");
var StreetAdress=$("#StreetAdress");
var City=$("#City");
var Province=$("#Province");
var Organization=$("#Organization");
var email=$("#email");
var phone=$("phone");
var checkedroles=$("#checkedroles");
var selected = new Array();
function checkCommentsForm(){
return true;
}
$("input:checkbox[name=checkedroles]:checked").each(function() {
selected.push($(this).val());
});
//When form submitted
$("#Reg").submit(function(){
if(checkCommentsForm()){
$.ajax({
type: "post",
url: "loginProcess.jsp",
data: {user : UserName.val(), fname : FirstName.val(),lname : LastName.val()
,stAddress:StreetAdress.val(),city:City.val(),prov:Province.val(),org:Organization.val()
,mail:email.val(),ph:phone.val(),'ch[]':selected},
success: function(data) {
}
});
}
});
});
also pls tell me how to retrieve the array in the servlet
You haven't shown your HTML but from the looks of it, it seems like these values are in a form.
You could then use ('#Reg').serialize() instead. This will Encode a set of form elements as a string for submission. - it will include all successful controls so all checked checkboxes will be included automatically as will all enabled text fields.
$("#Reg").submit(function(){
if(checkCommentsForm()){
$.ajax({
type: "post",
url: "loginProcess.jsp",
data: $(this).serialize(),
success: function(data) {
}
});
}
});
To retrieve the submitted values in your servlet, use the ServletRequest#getParameter() and ServletRequest#getParameterValues() methods. The former for when you have just one value for a parameter (for example, a test field) and the latter when you can have multiple values with that parameter name, for example, multiple checkboxes with the same name as is the case in your question. So you'd write something like this in your servlet:
String [] checked = request.getParameterValues("checkboxname");

Categories