Pass variable from JSP to Javascript - javascript

Inside a JSP, I am fetching data from a Servlet by this code
<%
String name=(String)request.getAttribute("filepath");
%>
I want to access this inside script tags, how should i go about it?
I tried this var n = "${name}" and var n = "<%=name%>" and it did not work.

Make sure the assignment in scriptlet is working. Try System.out.println(name); to see if the value is set correctly.
I often use the latter
var n = "<%=name%>";

Both options should work fine (do not forget the ;).
Just remember that the scriptlet/ EL are executed when the page is returned from the server and the JavaScript when the browser parse the HTML.
To debug this issue I would use scriptlet first and look if I have a value using browser "view source".
If you do not see any value i.e.
var n = "";
You did not set the attribute correctly in java.
As for EL usage. Make sure you have the correct setting, in older version EL was disabled by default see
http://www.mkyong.com/spring-mvc/modelandviews-model-value-is-not-displayed-in-jsp-via-el/

Related

JavaScript - How to evaluate an EL with a JS variable inside? [duplicate]

I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.

How to use dynamically generated javascript in an SRC attribute?

I have some Javascript, which generates other Javascript code and puts it in a string:
var my_string = "alert('Hello World!');";
(This is a gross oversimplicication of how I am actually getting a string that contains JS code, but needless to say, via a process that is too long to describe, I end up with one - this isn't something I can change.)
What I want to do is figure out a way to use the Javascript that's contained in that string in the SRC attribute of a new SCRIPT tag that I'm going to write to the document head. For reasons I can't explain, I can't write it inline.
I tried using HTML5 local storage to do this, like so:
// Store
localStorage.setItem('hello', my_string);
// Access
var s = document.createElement('script');
s.setAttribute("type","text/javascript");
s.setAttribute("src", "javascript:localStorage.getItem('hello')");
document.head.appendChild(s);
But apparently it just doesn't work that way. Can't use IDBObjectStore for the same reason.
I also looked into using the HTML5 FileSystem API, which would do exactly what I need to solve this problem, but that only works in Chrome. I need my code to work in Firefox.
Is there any way to achieve this?
The src attribute has to reference a file that is loaded and evaluated as JavaScript. If you want to evaluate a string as JavaScript, just use eval:
eval("localStorage.getItem('hello')");
Of course you should only do this if the input is trustworthy. Otherwise this is a big security hole.
In case you really want to use a script tag, you have to set the code as content of the element:
var s = document.createElement('script');
s.text = "localStorage.getItem('hello')";
document.head.appendChild(s);

saving value from form doesn't work

So, storing a Java String into a form hidden input value. I call said value via javascript and attempt to store it into a var. Strangely, I can display the value via alert but javascript crashes when I try to save it into a var.
The first line is from the initializing jsp file. It does some stuff that gets the string. The string is a list of ints that I plan on splitting in javascript for some stuff.
"<form id = \"listArrForm\"> <input id = \"listArr\" value = "+ output +" type = \"hidden\"></form>"
var listArr = document.getElementById("listArr").value; //Does work
alert(document.getElementById("listArr").value); //Does work
So yea, I'm guessing it has to do with the the type of value being retrieved?
Well, both should work as you can see in this jsfiddle: http://jsfiddle.net/2eWja/
What are you storing in the value that makes the script not work? Are you sure you're not putting quotes in?
what browser are you using? There could be problem for some
Btw using getElementById is known to be wrong. ;)

JavaScript literal insert vaule? (Too many characters in character literal)

Ok so in my mvc View my "Model" is a list of objects and in this case i want to get a specific Id of one of the objects.
var counter = 0; //for example
var id = '<%=Model[' + counter + '].Id %>';
This is what i get :
Compiler Error Message: CS1012: Too many characters in character literal
Thanks!
Yes, the counter variable can't be used as the index for Model[], because it only exists on the client (assuming this snippet was inside of a script html element). When you are creating a view, it might be useful to think of it as a long 'string' that you are constructing (the html returned to the browser). In this case 'counter' is just some characters in your script block that will eventually be interpreted by the browser, so it's not a variable that can be used while building the view. The <%= %> block just returns a string to append (that's what the = sign does).
Perhaps you intended to have the counter variable in it's own C# code block like so:
<% var counter = 0; %>
<script language=javascript>
var id = '<%=Model[counter].Id %>';
</script>
That doesn't really make any sense. You're trying to put together an ASP expression with client-side Javascript in the middle of it. It's nonsensical because the ASP stuff all runs on your server, while the Javascript runs in the client.
Without knowing the rest of what you want to do, it's hard to say how you should proceed.

VBScript: Using a variable within a DOM element

I'm looking to use a VBScript variable within a reference to a DOM element for a web-app I'm building. Here's a brief excerpt of the affected area of code:
dim num
num = CInt(document.myform.i.value)
dim x
x = 0
dim orders(num)
For x = 0 To num
orders(x) = document.getElementById("order" & x).value
objFile.writeLine(orders(x))
Next
This is my first venture into VBScript, and I've not been able to find any methods of performing this type of action online. As you can see in the above code, I'm trying to create an array (orders). This array can have any number of values, but that number will be specified in document.myform.i.value. So the For loop cycles through all text inputs with an ID of order+x (ie, order0, order1, order2, order3, order4, etc. up to num)
It seems to be a problem with my orders(x) line, I don't think it recognizes what I mean by getElementById("order" & x), and I'm not sure exactly how to do such a thing. Anyone have any suggestions? It would be much appreciated!
I was able to get this working. Thanks to both of you for your time and input. Here is what solved it for me:
Rather than using
document.getElementById("order" & x).value
I set the entire ID as a variable:
temp = "order" & x
document.getElementById(temp).value
It seems to be working as expected. Again, many thanks for the time and effort on this!
I can only assume that this is client side VBScript as document.getElementById() isn't accessible from the server.
try objFile.writeLine("order" & x), then check the source to make sure all the elements are in the document.
[As I can't put code in comments...]
That is strange. It looks to me like everything should be working.
Only other thing I can think of is: change
orders(x) = document.getElementById("order" & x).value
objFile.writeLine(orders(x))
to
orders(x) = document.getElementById("order" & x)
objFile.writeLine(orders(x).value)
It looks as if you're mixing client vs server-side code.
objFile.writeLine(orders(x))
That is VBScript to write to a file, which you can only do on the server.
document.getElementById
This is client-size code that is usually executed in JavaScript. You can use VBScript on IE on the client, but rarely does anyone do this.
On the server you'd usually refer to form fields that were part of a form tag, not DOM elements, (assuming you're using classic ASP) using request("formFieldName").
To make server-side stuff appear on the client (when you build a page) you'd embed it in your HTML like this:
<% = myVariable %>
or like this (as part of a code block):
document.write myVariable
Don't you need to change your loop slightly?
For x = 0 To num - 1
E.G. With 4 items you need to iterate from 0 to 3.

Categories