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.
Related
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 have servlet calling in ajax call. It send json object in response. Now I have receive this json in jsp and place data in table format. Can someone help me in this. Here is my code,
I am calling servlet as,
xmlHttpReqRM.open('POST', "RTMobitor?rtype=rmonitor", true);
my servlet, Here vehicleList is a list object
latlng.setLng(resultSet.getString("lng"));
latlng.setStatus(resultSet.getString("status"));
latlng.setRdate(resultSet.getString("rdate"));
latlng.setRtime(resultSet.getString("rtime"));
vehicleList.add(latlng);
System.out.println(vehicleList);
String json = new Gson().toJson(vehicleList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Previously I was sending response as a text, it was easy but now I changed to json. I am not getting how to receive,
xmlHttpReqRM.onreadystatechange = function() {
if (xmlHttpReqRM.readyState == 4) {
if (xmlHttpReqRM.status == 200) {
var responceeString = xmlHttpReqRM.responseText; // How to replace this ajax code for json
document.getElementById("flexme1").innerHTML = (responceeString);
} else {
alert('ERR OR: AJAX request status = ' + xmlHttpReqRM.status);
}
How can I replace this ajax code for json. Can anyone help me in this please.
var jsonObject = JSON.parse(responceeString);
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);
}
I'm trying to retrieve JSON object using jQuery get, and the Object I retrieve I want to embed in innerHTML. The following code is how i construct my JSON
getListOfActivity.jsp
<%
String urusStr = request.getParameter("ukid");
int urusId = Integer.parseInt(urusStr);
lkpPdkCommon[] activity = getListOfActivity(urusId);
if(activity!=null){
out.println("{PartList:");
out.println("[");
for(int x=0;x<2;x++){// the lkpPdkCommon[] return from getListOfActivity(urusId) huge so I limit the array to 2
out.println("{");
out.println("ActivityID:\""+activity[x].getID()+"\",Description:\""+activity[x].getDescription()+"\"");
out.println("}");
if((x+1)!=2){
out.println(",");
}
}
out.println("]");
out.println("}");
response.setContentType("application/json");
%>
and below code is my jQuery/jscript
var ukid = document.getElementById("ukid").value
var aktivityId = row.insertCell(1);
var description = row.insertCell(2);
var JSONObject;
var $ac = jQuery.noConflict();
$ac.get("../../getListOfActivity.jsp",{ukid:ukid}, function(data){
JSONObject = data
//for testing purposes I do not iterate through the JSON Object
aktivityId.innerHTML = JSONObject.PartList[0].ActivityID
description.innerHTML = JSONObject.PartList[0].Description
});
The following code didn't return any error, but it seems doesn't work. This is the JSON Object I check using firebug
Have you tried Jquery getJSON.
I think this would help you.
http://api.jquery.com/jQuery.getJSON/
The problem solved after I modified the following line in jsp
out.println("{PartList:");
to
out.println("{\"PartList\":");
and
out.println("ActivityID:\""+activity[x].getID()+
"\",Description:\""+activity[x].getDescription()+"\"");
to
out.println("\"ActivityID\":\""+activity[x].getID()+
"\",\"Description\":\""+activity[x].getDescription()+"\"");
The original JSON object send by response header before I do the modification are like below:
{PartList:
[
{ActivityID:"8638",Description:"GERMS"},
{ActivityID:"8639",Description:"GOVERNMENT CERTIFY PROGRAMMES"}
]
}
and after the modification
{"PartList":
[
{"ActivityID":"8638","Description":"GERMS"},
{"ActivityID":"8639","Description":"GOVERNMENT CERTIFY PROGRAMMES"}
]
}
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");