Good Evening, I try to do a checkbox which embedded in a JSP page. I use document.getElementByID("checkbox") in the JSP javascript function. How to pass the variables in the javascript function to another java file without passing it through url for security concern?
This is Checkbox Function:
var checkbox = document.getElementById("chbx");
function foo(){
if(checkbox.checked=true){
//passThisVariableToAnotherJavaFile-isChecked
}
else {
//passThisVariableToAnotherJavaFile-isNotChecked
}
};
This is Java File:
public class CheckBoxEvent{
if(isChecked) {
//then whatever
} else if (isNotChecked) {
//then no whatever
}
}
I am a newbie is this jsp stuff, I used to be doing this in PHP but everything mixed-up in my mind when there is a HashMap appear in the java file. Well, need some hints and help.
Thank You
How to pass the variables in the javascript function to another java file without passing it through url for security concern?
You have two options here and in both the cases you need to send the value to the server for processing :
An AJAX POST or GET request. This looks more appropriate to your requirement. You can get an example here.
Submit the form using POST.
Read here When do you use POST and when do you use GET?
In both the cases , there will be a Servlet/JSP/Controller handling the request in the server. You can call the methods in your Custom Java class with the request parameters.
when you do var checkbox = document.getElementById("chbx"); you are doing it at client side. Now if you want to propagate this value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-
1)Make an AJAX call. (You can also use jquery here to make AJAX call).Here is
the small example, you can find ample on google
$.ajax({
type: 'GET',
dataType: 'json',
url: servlerURL,
success: function(reply) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
or
2)Submit the form
Related
I am unable to get the string response from the java function to the ajax call. I am using structs2 . I have wrote a java function that returns a string. the function works properly. but there are some unknown error in the ajax call.
following is my jquery ajax call
<pre>
function saveMyId(){
$.ajax({
url : contextPath+'/action/setMyId',
data: {
myCode:$("#myCode").val(),
myId:$("#myId").val()
},
type : 'post',
async: false,
success : function(data) {
alert(data);
if(data=="success"){
$( "#dialog" ).dialog("close");
$('#myId_Validator').text("");
}
else{
$("#myId").val("");
$("#myId_Validator").val("ID Already exists. Please Choose different one")
}
},
error: function (request, status, error) {
alert("Something went wrong. Please try again later");
}
});
and my java function is
public String setMyId() throws SQLException {
IdAllocationVO idAllocationVO = new IdAllocationVO();
MyIdServices myIdServices = new MyIdServices();
logger.debug("set My Id , myCode :"+this.myCode);
idAllocationVO.setMyCode(myCode);
idAllocationVO.setMyId(myId);
int response= myIdServices.getMyIdCount(myId);
System.out.println("response:"+response);
if(response==0){
myIdServices.setSenderId(idAllocationVO);
return "success";
}
else{
return "fail";
}
}
I am using structs 2
and the structs.xml tag is
<action name="setMyId" class="com.id.myIsservice.struts.IdAction" method="setMyId">
</action>
The function setMyId() is working correctly. I have checked everything by printing each line. But my issue is the ajax call gets the result as an error. so it alerts the error message "Something went wrong. Please try again later". Why it is so?
there are three steps you can try to use for finding the reason:
1、If your ajax call is correct?
firebug or other page dubugger can show you~
2、When the 1st step is correct, check the java function to see if it gets the request from page and responses the right result to page
IDE debug tools will help you~
3、Check what results are got by page
through firebug you can see the response details, like 'status' and others..., findout if the string has been got~
PS:
I see, your java code throw exceptions directly without using try/catch. It's not a good way for users' use~ I suggest you to add try/catch code, with whith maybe help you find error quicker~
weird problem here I can't seem to solve.
I'm working in Eclipse Java EE, I have a servlet called Process (mapped to /process)
There is a link to process
Checkout
Within process is a doGet method, verifying there is a user logged in, which redirects to a checkout page. (this works) The checkout page contains items, each with an individual input, and I have a seperate doPost method which updates the DB.. obtaining the input to update as follows
<input id='ID created in servlet' value='decided in servlet'>
followed by
<button id="update">Button</button>
I have the following JS
var json = [];
$('#update').click(function(){
$('.items').find('input').each(function(){
var tmp = "{id:" + $(this).attr('id') + ",quantity:" + $(this).val() + "}";
json.push(tmp);
});
$.ajax( {
url : 'process',
type : 'POST',
data : json,
dataType : 'json',
success: function(data) {
alert("success");
}
});
});
So, two questions I guess.
First, this is sending a request to a different servlet, in a different project. However when accessed using a doGet, it works. (I have different code for a doPost) Is there any reason it's not recognizing the doPost method within my Process.java file? What could cause it to search for another servlet?
Second, I know what to do once I get the data in the servlet, but I don't know how to actually access the data. It's passed through jquery in 'data:', then how would I access it in the servlet?
First Question:
If i have understood right, Your problem is that "when you try to send a post request using AJAX (inside a jquery function), you are not hitting the desired servlet".
Solution: You need to append the name of your project to the url.
So lets say your servlet is placed in project named "SomeProject" and the servlet is mapped to url named "servletProcess".
So your jQuery should look something like this:
var json = [];
$('#update').click(function(){
$('.items').find('input').each(function(){
var tmp = "{id:" + $(this).attr('id') + ",quantity:" + $(this).val() + "}";
json.push(tmp);
});
$.ajax( {
url : '/SomeProject/servletProcess',
type : 'POST',
data : json,
dataType : 'json',
success: function(data) {
alert("success");
}
});
});
This should fix the problem :)
Second Question: try this Similar Query
I have a Scriptlet inside a function , which gets data from a Session and checks for a value inside the Map
Can i pass the User Selected Option which is a javascript variable to a Map ??
function checker()
{
var selObj = document.getElementById('selSeaShells');
var optionselectedvalue = selObj.options[selObj.selectedIndex].value.split(':')[0];
if(optionselectedvalue==''||optionselectedvalue==null)
{
alert('Select a Book');
return false;
}
if (!text_form.quan.value)
{
alert('Enter Quantity');
return false;
}
var selectedbook = optionselectedvalue;
var selectedquantity = text_form.quan.value;
<%
Map cart = (Map) session.getAttribute("cart");
if(cart.containsKey(selectedbook))
{
String quant = (String) cart.get(str);
}
%>
return true;
}
javascript plays on client side and JSP plays on server side.
What you need is you have to make a server request. And send that string a query parameter.
You might misunderstand that jsp and javascript existed on same document. Yes but JSP part compiles on server side itself and JSP output is sent to the client.
So solutions are: either go for html form submit or go for Ajax request.
java processing is done at server side and javacript executes on client side. If you do view source on html page you wont find any map.So you can not pass the javascript value to java code (as java code has already been processed by server and its no more).
If you are really want to pass the javascript value to server side you can take help help of ajax or form submission as Baadshah pointed above
From current JSP I need to open new page with sending to it POST data. How I can make it?
In other words I need redirect from one page to another, but I cant use sendRedirect(because only GET) and requestDispatcher(because context of pages are different)
You have to create <form method="post">, fill the fields with respective data and submit it by JavaScript.
But on the other hand, what is your reason for that? There probably exists a cleaner solution.
Just make the behaviour that would happen if the initial POST data is received the default behaviour of the JSP when no post data is received.
e.g (in pseudo code - I don't know Java)
if (is_set(POST) ) {
if(POST == expectedInitialVals) {
defaultBahaviour();
} else {
handleOtherValues();
}
} else {
defaultBahaviour();
}
If you also want to persist the POST data in the page set the values on the relevant form fields in the page in your JSP.
I'm facing this problem with regards to Forms and Requests. I'm using sencha and javascript to create a webpage that POSTs a form to a java web application which pulls data from a database and formats it before returning a html page to the client.
The problem I'm facing is that for some reason, while the form does get filled(checked using the debugger in chrome), the java program does not recognise the parameter within the form, and instead reads it as null.
I'm following the method of setting the form from an old java program, which works, however it fails for mine. Does anyone know how I can solve this or where I might be doing wrong?
I've included the javascript and java codes where I decide which page to return below.
Javascript handler for function call to submit form:
var MenuA = function() {
simple.getComponent('flag').setValue('MenuA');
simple.getEl().dom.action = './Soap';
simple.getEl().dom.method = 'POST';
simple.submit();}
Java code to decide choice of page:
if (request.getParameter("flag").matches("MenuA")) {
choice = 2;
} else if (request.getParameter("flag").matches("MenuB")) {
choice = 3;}
FormPanel Code:
var simple = new Ext.form.FormPanel({hidden:true,standardSubmit:true,
items:[
{xtype: 'textfield', hidden: true, name : 'password', label: 'Password', id:'password'}
,{xtype: 'textfield', hidden: true, name : 'user', label: 'user', id:'user'}
,{xtype: 'textfield', hidden: true, name: 'flag', label: 'flag', id: 'flag'}]})
Your
request.getParameter("flag").matches("MenuA");
method is looking for a form element whose name is "flag".
Since your form may not contain the flag field so it assumes it to be null.
So, to overcome you can add an input field to the form with name "flag" and put put your desired value in it.
I think this should work for you.
Nevermind. Found the problem. I didn't realise the form was not being sent properly. Sorry for the trouble!