Assign Javascript value to a java String in a jsp [duplicate] - javascript

Can anyone tell me how to pass JavaScript values to Scriptlet in JSP?

I can provide two ways,
a.jsp,
<html>
<script language="javascript" type="text/javascript">
function call(){
var name = "xyz";
window.location.replace("a.jsp?name="+name);
}
</script>
<input type="button" value="Get" onclick='call()'>
<%
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}
%>
</html>
b.jsp,
<script>
var v="xyz";
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("value="+st);
%>

Your javascript values are client-side, your scriptlet is running server-side. So if you want to use your javascript variables in a scriptlet, you will need to submit them.
To achieve this, either store them in input fields and submit a form, or perform an ajax request. I suggest you look into JQuery for this.

simple, you can't!
JSP is server side, javascript is client side meaning at the time the javascript is evaluated there is no more 'jsp code'.

I've interpreted this question as:
"Can anyone tell me how to pass values for JavaScript for use in a JSP?"
If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.
<html>
<body>
<script type="text/javascript">
var serverInfo = "<%=getServletContext().getServerInfo()%>";
alert("Server information " + serverInfo);
</script>
</body>
</html>

You cannot do that but you can do the opposite:
In your jsp you can:
String name = "John Allepe";
request.setAttribute("CustomerName", name);
Access the variable in the js:
var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);

If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.
Other wise you can't do it.

Its not possible as you are expecting. But you can do something like this. Pass the your java script value to the servlet/controller, do your processing and then pass this value to the jsp page by putting it into some object's as your requirement. Then you can use this value as you want.

This is for other people landing here.
First of all you need a servlet. I used a #POST request.
Now in your jsp file you have two ways to do this:
The complicated way with AJAX, in case you are new to jsp:
You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:
$(document).ready(function() {
var sendVar = "hello";
$('#domId').click(function (e)
{
$.ajax({
type: "post",
url: "/", //or whatever your url is
data: "var=" + sendVar ,
success: function(){
console.log("success: " + sendVar );
<%
String received= request.getParameter("var");
if(received == null || received.isEmpty()){
received = "some default value";
}
MyJavaClass.processJSvar(received);
%>;
}
});
});
});
The easy way just with JSP:
<form id="myform" method="post" action="http://localhost:port/index.jsp">
<input type="hidden" name="inputName" value=""/>
<%
String pg = request.getParameter("inputName");
if(pg == null || pg.isEmpty()){
pg = "some default value";
}
DatasyncMain.changeToPage(pg);
%>;
</form>
Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).

I Used a combination of the scriptlet, declaration, and expression tags...
<%!
public String st;
%>
<%
st= "<html> <script> document.writeln('abc') </script> </html>";
%>
<%=
" a " + st + " <br> "
%>
The above code is working completely fine in my case.

Related

Why is EJS replacing " with &#34 when sending JSON string to Javascript Variable in html code [duplicate]

I'm working on a Node.js app (it's a game). In this case, I have some code set up such that when a person visits the index and chooses a room, he gets redirected to the proper room.
Right now, it's being done like this with Express v2.5.8:
server.get("/room/:name/:roomId, function (req, res) {
game = ~databaseLookup~
res.render("board", { gameState : game.gameState });
}
Over in board.ejs I can access the gameState manner with code like this:
<% if (gameState) { %>
<h2>I have a game state!</h2>
<% } %>
Is there a way for me to import this into my JavaScript logic? I want to be able to do something like var gs = ~import ejs gameState~ and then be able to do whatever I want with it--access its variables, print it out to console for verification. Eventually, what I want to do with this gameState is to display the board properly, and to do that I'll need to do things like access the positions of the pieces and then display them properly on the screen.
Thanks!
You could directly inject the gameState variable into javascript on the page.
<% if (gameState) { %>
<h2>I have a game state!</h2>
<script>
var clientGameState = <%= gameState %>
</script>
<% } %>
Another option might be to make an AJAX call back to the server once the page has already loaded, return the gameState JSON, and set clientGameState to the JSON response.
You may also be interested in this: How can I share code between Node.js and the browser?
I had the same problem. I needed to use the data not for just rendering the page, but in my js script. Because the page is just string when rendered, you have to turn the data in a string, then parse it again in js. In my case my data was a JSON array, so:
<script>
var test = '<%- JSON.stringify(sampleJsonData) %>'; // test is now a valid js object
</script>
Single quotes are there to not be mixed with double-quotes of stringify. Also from ejs docs:
"<%- Outputs the unescaped value into the template"
The same can be done for arrays. Just concat the array then split again.
I feel that the below logic is better and it worked for me.
Assume the variable passed to the ejs page is uid, you can have the contents of the div tag or a h tag with the variable passed. You can access the contents of the div or h tag in the script and assign it to a variable.
code sample below : (in ejs)
<script type="text/javascript">
$(document).ready(function() {
var x = $("#uid").html();
alert(x); // now JS variable 'x' has the uid that's passed from the node backend.
});
</script>
<h2 style="display:none;" id="uid"><%=uid %></h2>
In the EJS template:
ex:- testing.ejs
<html>
<!-- content -->
<script>
// stringify the data passed from router to ejs (within the EJS template only)
var parsed_data = <%- JSON.stringify(data) %>
</script>
</html>
In the Server side script:
ex: Router.js
res.render('/testing', {
data: data // any data to be passed to ejs template
});
In the linked js (or jquery) script file:
ex:- script.js
In JavaScript:
console.log(parsed_data)
In JQuery:
$(document).ready(function(){
console.log(parsed_data)
});
Note:
1. user - instead of = in <% %> tag
2. you can't declare or use data passed from router to view directly into the linked javascript or jquery script file directly.
3. declare the <% %> in the EJS template only and use it any linked script file.
I'm not sure but I've found it to be the best practice to use passed data from router to view in a script file or script tag.
This works for me.
// bar chart data
var label = '<%- JSON.stringify(bowlers) %>';
var dataset = '<%- JSON.stringify(data) %>';
var barData = {
labels: JSON.parse(label),
datasets: JSON.parse(dataset)
}
You can assign backend js to front end ejs by making the backend js as a string.
<script>
var testVar = '<%= backEnd_Var%>';
</script>
This should work
res.render("board", { gameState : game.gameState });
in frontend js
const gameState = '<%- JSON.stringify(gameState) %>'
Well, in this case you can simply use input text to get data. It is easy and tested when you use it in firebase.
<input type="text" id="getID" style="display: none" value="<%=id%>">
I know this was answered a long time ago but thought I would add to it since I ran into a similar issue that required a different solution.
Essentially I was trying to access an EJS variable that was an array of JSON objects through javascript logic like so:
<script>
// obj is the ejs variable that contains JSON objects from the backend
var data = '<%= obj %>';
</script>
When I would then try and use forEach() on data I would get errors, which was because '<%= obj %>' provides a string, not an object.
To solve this:
<script>
var data = <%- obj %>;
</script>
After removing the string wrapping and changing to <%- (so as to not escape html going to the buffer) I could access the object and loop through it using forEach()
Suppose you are sending user data from the node server.
app.get("/home",isLoggedIn,(req,res)=>{
res.locals.pageTitle="Home"
res.locals.user=req.user
res.render("home.ejs");
})
And now you can use the 'user' variable in the ejs template. But to use the same value using client-side javascipt. You will have to pass the data to a variable in the tag.
Passing ejs variable to client-side variable:
<script>
let user= '<%- JSON.stringify(user) %>';
</script>
<script>home.js</script>
Now you can access the user variable at home.js

Submitting a javascript object to vbScript and referencing its properties in classic ASP

I've never passed a JavaScript object to an .asp page. Can someone give me the syntax here. I've tried googling w/o success. The object is called buyerInfo. Using jQuery.
<form id="aform" action="formact.asp" method="POST">
<input type="hidden" id="myhid" name="myhid" value="">
<input type="submit">
</form>
<script>
buyerInfo = {};
buyerInfo.name = "Joe Buyer"
buyerInfo.zip = "12345"
$("#myhid").val(buyerInfo);
</script>
-- and in formact.asp
<%
Set buyer = Request("myhid")
name = buyer.name
%>
yields
Object doesn't support this property or method: 'buyer.name'.
What is the correct way to reference these? I know the JavaScript object is being passed, but I don't know how to access its pieces. Thanks.
You could get away without using any Classic ASP libraries
jQuery
$.post('/process.asp', {
name: buyerInfo.name,
zip: buyerInfo.zip
}, function (data) {
}).done(function (data) {
alert(data); // Data that is returned by the ASP pae
});
ASP
dim name : set name = request.form("name")
dim zip: set zip= request.form("zip")
Classic ASP does not have JSON or object's (at least in this sense) built-in by default and you have to load other libraries.
I suggest including this ASP JSON library at the top of formact.asp :
https://github.com/nagaozen/asp-xtreme-evolution/blob/master/lib/axe/classes/Parsers/json2.asp
and then passing the value like this:
<%
Dim buyer : set buyer = JSON.parse(request.form("myhid"))
name = buyer.name
%>

How to pass an argument from javascript to a Servlet through JSP

I'd like to do something like that
function(){
<% ExampleClass sample = new ExampleClass(); %>
var ID = 4;
var something = <%= sample.getSomethingById(ID) %>
}
How can I pass this ID to the jsp expression?
Thanks for any suggestion, and sorry id the question is not so well formulated.
you can also use more advanced methods and tools, like Ajax and JQuery:
function submitToJsp(){
$.ajax({
type: 'POST',
url: 'mypage.jsp',
data: {
id: '123',
comment:$('#comment').val()
},
beforeSend:function(){
// this is where we append usually a loading image
},
success:function(data){
// successful request; do something with the data
$('#output').html(data);
},
error:function(){
// failed request; give feedback to user
}
});
}
In short, by calling the function submitToJsp(); we send an asynchronous (ajax) request to the mypage.jsp jsp with 2 parameters.
use hidden variable and then put the id into that variable.You can not pass using the code above.
<input type="hidden" name="test" value="your id" />
Then you can access like request parameter.
Your javascript code is not executed until after the JSP page has been rendered. So any java variables you want to access in your script needs to be pre-rendered as a javscript variable. After the page has been rendered, you can't execute java code in your javascript. You can't "share" variables between java code and javascript like that. Your example is probably simplified, but in this case, you could just do
var something = <%= sample.getSomethingById(4) %>
You should use hidden field :-
<input type="hidden" name="hdtest" id="idtest" value="<%=sample.getSomethingById(ID) %>" />
Now inside javascript try to access the value.
Try this code in java script :
var something = document.getElementById('idtest').value;
Hope it will help you.

How to insert JavaScript variable in JSP String variable

How to insert JavaScript variable in JSP String variable.
<script>
<%!
String host_name = "tst" + location.host;
%>
</script>
<%=host_name%> <!-- getting error -->
Thanks for help.
Javascript is executed in the browser, and JSP on the server. So you can't directly get a value from javascript into JSP (java) : when the javascript is executed, JSP has finished its execution and sent the result.
Depending on your need, you may want to send a value using ajax from the browser to the server but it's impossible to define the applicable strategy without knowing why you tried this.
If what you want is just have your hostname in java/jsp, I'd suggest you to do something along the lines of
<%
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
%>

Accessing EJS variable in Javascript logic

I'm working on a Node.js app (it's a game). In this case, I have some code set up such that when a person visits the index and chooses a room, he gets redirected to the proper room.
Right now, it's being done like this with Express v2.5.8:
server.get("/room/:name/:roomId, function (req, res) {
game = ~databaseLookup~
res.render("board", { gameState : game.gameState });
}
Over in board.ejs I can access the gameState manner with code like this:
<% if (gameState) { %>
<h2>I have a game state!</h2>
<% } %>
Is there a way for me to import this into my JavaScript logic? I want to be able to do something like var gs = ~import ejs gameState~ and then be able to do whatever I want with it--access its variables, print it out to console for verification. Eventually, what I want to do with this gameState is to display the board properly, and to do that I'll need to do things like access the positions of the pieces and then display them properly on the screen.
Thanks!
You could directly inject the gameState variable into javascript on the page.
<% if (gameState) { %>
<h2>I have a game state!</h2>
<script>
var clientGameState = <%= gameState %>
</script>
<% } %>
Another option might be to make an AJAX call back to the server once the page has already loaded, return the gameState JSON, and set clientGameState to the JSON response.
You may also be interested in this: How can I share code between Node.js and the browser?
I had the same problem. I needed to use the data not for just rendering the page, but in my js script. Because the page is just string when rendered, you have to turn the data in a string, then parse it again in js. In my case my data was a JSON array, so:
<script>
var test = '<%- JSON.stringify(sampleJsonData) %>'; // test is now a valid js object
</script>
Single quotes are there to not be mixed with double-quotes of stringify. Also from ejs docs:
"<%- Outputs the unescaped value into the template"
The same can be done for arrays. Just concat the array then split again.
I feel that the below logic is better and it worked for me.
Assume the variable passed to the ejs page is uid, you can have the contents of the div tag or a h tag with the variable passed. You can access the contents of the div or h tag in the script and assign it to a variable.
code sample below : (in ejs)
<script type="text/javascript">
$(document).ready(function() {
var x = $("#uid").html();
alert(x); // now JS variable 'x' has the uid that's passed from the node backend.
});
</script>
<h2 style="display:none;" id="uid"><%=uid %></h2>
In the EJS template:
ex:- testing.ejs
<html>
<!-- content -->
<script>
// stringify the data passed from router to ejs (within the EJS template only)
var parsed_data = <%- JSON.stringify(data) %>
</script>
</html>
In the Server side script:
ex: Router.js
res.render('/testing', {
data: data // any data to be passed to ejs template
});
In the linked js (or jquery) script file:
ex:- script.js
In JavaScript:
console.log(parsed_data)
In JQuery:
$(document).ready(function(){
console.log(parsed_data)
});
Note:
1. user - instead of = in <% %> tag
2. you can't declare or use data passed from router to view directly into the linked javascript or jquery script file directly.
3. declare the <% %> in the EJS template only and use it any linked script file.
I'm not sure but I've found it to be the best practice to use passed data from router to view in a script file or script tag.
This works for me.
// bar chart data
var label = '<%- JSON.stringify(bowlers) %>';
var dataset = '<%- JSON.stringify(data) %>';
var barData = {
labels: JSON.parse(label),
datasets: JSON.parse(dataset)
}
You can assign backend js to front end ejs by making the backend js as a string.
<script>
var testVar = '<%= backEnd_Var%>';
</script>
This should work
res.render("board", { gameState : game.gameState });
in frontend js
const gameState = '<%- JSON.stringify(gameState) %>'
Well, in this case you can simply use input text to get data. It is easy and tested when you use it in firebase.
<input type="text" id="getID" style="display: none" value="<%=id%>">
I know this was answered a long time ago but thought I would add to it since I ran into a similar issue that required a different solution.
Essentially I was trying to access an EJS variable that was an array of JSON objects through javascript logic like so:
<script>
// obj is the ejs variable that contains JSON objects from the backend
var data = '<%= obj %>';
</script>
When I would then try and use forEach() on data I would get errors, which was because '<%= obj %>' provides a string, not an object.
To solve this:
<script>
var data = <%- obj %>;
</script>
After removing the string wrapping and changing to <%- (so as to not escape html going to the buffer) I could access the object and loop through it using forEach()
Suppose you are sending user data from the node server.
app.get("/home",isLoggedIn,(req,res)=>{
res.locals.pageTitle="Home"
res.locals.user=req.user
res.render("home.ejs");
})
And now you can use the 'user' variable in the ejs template. But to use the same value using client-side javascipt. You will have to pass the data to a variable in the tag.
Passing ejs variable to client-side variable:
<script>
let user= '<%- JSON.stringify(user) %>';
</script>
<script>home.js</script>
Now you can access the user variable at home.js

Categories