How to pass javascript variable value to java class - java

I want to submit data from a html page to java class. I am using javascript to get data from html page, now I want to send this data to java class to save this data to db. I am using ftl template to generate html so I cant use jsp here. Please give an example using either javascript of ajax or jquery.
thanks.

You can use jquery to send an ajax request to your Java servlet.
$.ajax({
type: "POST",
url: "/app/servlet/",
data: {name : "John", location : "Boston"},
success: function(msg){
alert( "Data Saved: " + msg );
}
});

Related

How to update an array Javascript from and array JSP

I need to update a javascript array everytime there is and event, like a click intercept with JQuery. I need that new value from JSP array come into an array javascript.
I know there are solutions like this Passing array from .jsp to javascript function.
The problem is quite different: code linked run only once, when I need to update every time I intercept an event.
I can understand that problems is inside the translation from Servlet to HTML, it seems: once the Jsp variable take value the first time than they became "static code" and it can't change.
Could you suggest me some alternative or solution?
function update_coordinate_javascript()
{
<%
for (int s: mycord.getXY()[0]) {
%>
xyscript.push(<% out.print(s); %>);
<%
}
%>
}
$("#myB").click(function(){
$.ajax({
type: "POST",
url: "readXY.jsp", // Some elaborations
data: {incrementa:true},
dataType: "html",
success: function(msg)
{
alert("Ok");
},
error: function()
{
alert("Fail");
}
});
update_coordinate_javascript();
return false;
});
}
You cannot mix Javascript and JSP like you're trying in the update_coordinate_javascript function, because Javascript runs client-side and JSP server-side.
What you are doing in that function is printing the values that the JSP has in mycord at the time it runs on the server-side. You are printing those into the Javascript function (view source to confirm) and thus you are printing out Javascript code basically. And once you've done that, you have a Javascript function with a hardcoded list. So every time you call that function you're just populating the same hardcoded list.
Instead: The JSP you are calling in Ajax should print the array to the response either as JSon, XML, or as a string with a certain character reserved to be used as a separator, and Javascript should parse that.
$.ajax({
type: "POST",
url: "readXY.jsp", //print array as JSON, XML, or CSV-like text there
data: {incrementa:true},
dataType: "html", //change this to JSON, XML, or text as needed
success: function(msg)
{
//msg here is the response from the JSP you are calling,
//so whatever you print to response there
//is in this variable
alert("Ok");
update_coordinate_javascript(msg); //parse the msg in there
},
error: function()
{
alert("Fail");
}
});
Then obviously you need to take the JSP scriplet code out of update_coordinate_javascript and change it to Javascript code that parses the msg parameter which is passed in. How you will do that will depend on how you decide to format the output from the JSP you are calling in Ajax (i.e. whether you have it return CSV-like text, XML, HTML, or JSON).
So if you go with CSV, it could be as simple as:
function update_coordinate_javascript(msg)
{
var mycords = msg.split(",");
for(var i=0; i<mycords.length; i++)
{
xyscript.push(mycords[i]);
}
}

Can we use jQuery to work with Java objects OR does it manipulate DOM model only?

I have a very complex scenario where i need to change the java objects(basically HashMap ) from jquery get Request and get the response and print that in the jsp. User can send number of request and get seperate response from servlet based on request and display the data.
after every request i have to put the map in session and than in another request i get the same in session and do the updates and put it back in session.
JqueryGet(parameter) to Java.
Updating Hashmap according to parameter.
Putting hashmap in session . ( session.setAttribute("map",map))
sending response back to Jsp in jquery and print results in jsp.
Than another request send to Java .
it will get the map from session session.getAttribute("map",map) and than update the map based on new request .
Put the map again in session and so on....Than i have a submit button finally which will show the new data on the page and than update the server.
Is this the right approach ? My functionality is working fine as of now in Dev environment. But i am worried whether i should use DOM. if i will use DOM it will be very complex since i have to manipulate much values of Hashmap based on request.
Here is the jquery code :
$.ajax({
url: '<%=portalContext.createTemplateProcessURI()%>'
+'?s1='+ $("#networkBox1").val()+'&box1=Box1&tick=add&val1='+ allvs+'&s2='+ $("#networkBox2").val()+'&box2=Box2&val2='+ allvs,
type: 'get',
dataType: 'text',
async: false,
success: function(data) {
Processbox(data); // This function displaying the result.
}
});
dude, first of all, I think after you get your data from back end side, your java object has already changed to json object. I think your flow has no problem, because once you change to DOM, then all the data is send through front side but not back end side, if you use session, actually you handle your data at back end side, for me, I prefer the second one.
Here is my idea:
1.set a dom object in your page with the data get from your ajax
$(domId).val(value get from ajax);
2.If your don't want to show the data, use hidden type input in your jsp form
<input type="hidden" id="domId" name="domName">
3.once you click submit button, handle your data in your servlet
String data = request.getParameter("domName");
session.setAttributes("sessionData", data);
Hope this will help you.

Sending request parameter using javascript to Servlet located in other domain in JSP

I have a question about JSP-
I want to send request parameters from jsp to servlet located on other domain server using javascript.
I know,there are some security policy for javascript. Is it possible?
Specifically, what I try to do is that when i click some image tag at jsp on domain named www.helloWorld1.com , I want to send request parameter to other domain named www.helloWorld2.com/servlet as using javascript
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
url: "http://www.helloWorld2.com/servlet?callback=?",
data: {projectID:1},
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
Use jsonp which is used for cross domain support.. and in the landing servlet use
request.getParameter("projectID") to get the request parameter values

HTML from servlet response using ajax is not being executed in JSP page

My problem is kinda weird. I have a JSP page that calls servlet using JQuery/ajax on combobox change. Everything works fine, I get the response but html is displayed as text. Other thing worth mentioning is when I call servlet directly by URL, everything is fine.
Servlet response code:
for(int i=0;i<tabstr.length;i++){
wyjscie.println(i+": "+tabstr[i]+" <br>");
}
JSP ajax call:
$('#com2').change(function() {
$.get('filtr', function(responseText) {
$('#result').text(responseText);
});
});
result is an ID of a DIV inside JSP page. I've done some servlets without ajax in the past and I didn't encounter this problem before. Any idea how to deal with it?
you have to set as html not text try this
$('#result').html(responseText);
I think your server doesn't specify the mime type of the response. So you have to specify it or you can specify dataType in you ajax call.
$.ajax({
url : "myUrl",
dataType : "json",
data : {
param1 : value1,
}
});
ajax api:
dataType: The type of data that you're expecting back from the server. If none
is specified, jQuery will try to infer it based on the MIME type of
the response...

Avoiding html in servlet

I'm on a jsp page and I am doing an ajax call to a servlet which in return provides full html code to be displayed on page. It works fine but looks cluttered in servlet file to have multiple printWriter.write(...) lines with html code in it. It becomes hard to maintain as I have to create a large html code via servlet. Is there any other proper/better way to do this? I have cmobination of write html lines and logic in servlet and it will be hard to separate them.
The ajax call in jsp page:
$.ajax({
type: 'POST',
url: 'myServlet',
data: requestData,
dataType: "text",
}).done(function(responseData) {
$(divId).html(responseData);
});
Some code from servlet class:
.....
String username = user.getName();
if (username != null && !username.trim().isEmpty())
username = username.substring(0, username.indexOf(" "));
else
username = "";
printWriter.write("<span id=\"username_"+i+"\" style=\"display: none;\">"+ username +"</span>");
printWriter.write("<form action=\"\" method=\"post\" name=\"userClickForm_"+i +"\" id=\"userClickForm_"+i +"\">");
printWriter.write(" <input type=\"hidden\" name=\"userId\" value=\""+userId +"\"/>");
printWriter.write("</form>");
......
The main reason of mixing html code and business logic is I have to provide div id based on conditions and loop structure.
You should use some form of template or transformation technology. Since you're using jQuery and JSPs this can be either a server-side JSP or a client-side jQuery template plugin.
Early JSP MVC patterns take this form:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// read inputs
String foo = request.getParameter("foo");
// perform business logic
SomeResults results = new SomeDataSource().lookupDatabase(foo);
// place results into scope
request.setAttribute("results", results);
// dispatch to JSP to render results
request.getRequestDispatcher("result.jsp")
.forward(request, response);
}
This approach can be used with an AJAX call.
Alternatively, you can respond with JSON or XML data and parse this in the JavaScript, then use a JavaScript template engine to do something similar to the logic performed in the JSP.
You can avoid that by using MVC framework like STRUTS or SPRING.
Use xml rather than html on servlet and on jsp use success attribute of ajax call using jquery.... In my case its working, bt i have used type as 'GET'.
$.ajax({
url: ,
data: ,
type: ,
dataType: 'xml',
async: true,
success:function(xmlDoc)
{
var message = xmlDoc.getElementsByTagName("message");
message = message[0].firstChild.data;
}
});
And in Servlet use::
res.getWriter().write("<response><message>abcdefg</message></response>");
You should use JSP's. It will be on different pair of servlet/jsp request, not the request initiating ajax call.

Categories

Resources