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

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.

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.

Pass variable from JSP to 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/

getting error while passing value from javascript to scriplet in jsp

I have a requirement where i need to pass a value from Javascript to a Scriplet in a JSP. i am aware that javascript is executed on client side and jsp on the server side.i have searched online and googled a lot but till now i am not able to find a solution that i am looking for. The JSP code is as below. both javascript and scriplet are in same jsp.
<script type="text/javascript">
var strUrl = window.location.href;
var aps = strUrl.toLowerCase().indexOf("values");
var modifiedString = strUrl.substring(aps+8);
var v = strUrl.indexOf(modifiedString);
document.write(v);
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st);
if(st.equals("0")){
out.println("test");
%>
<h1><div class="xyz">
<fmt:message>header.txt</fmt:message>
</div></h1>
<%
}else{
%>
<div class="pqr">
<fmt:message>header1.txt</fmt:message>
</div>
<%
}
%>
In the above code i am trying to pass a value from Javascript to a scriplet.
But i am getting a NumberFormatException when i try to parse that string and convert to int. looks like the variable st is not of a string type.
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st)
Can you please let me know what is the problem with the above code and how can i resolve the problem that i am facing now.
Thanks
Vikeng
The reason why you can't parse "<script>document.writeln(v)</script>" as an int is because it contains characters other than digits.
Even though it looks like it contains <script> tags - it's still not code that will execute or evaluate to a number. Because it's in quotes it's just a string. So "<script>document.writeln(v)</script>" looks the same to the parser as would "tic/v)neiwtm>oprs<citdun.rtl(<rp>".
This is somewhat of a moot point however, because unfortunately, you can't pass values to scriptlets. It's completely one-directional.
In order to get your page communicating with your java, you'll need to pass your params while requesting some handler.
For example, you could do some asynchronous JavaScript:
var asyncHR = new XMLHttpRequest();
var URL = "https://www.yourserver.com/intparser?st=v";
asyncHR.open("GET", URL, true);
asyncHR.send();
Then your request handler could take that parameter st, parse it or whatever you need to do, modify the model - adding this new value as an attribute, and then from JavaScript, reload the page.

How to get the value of an ASP.net variable into a javascript textbox

I'm writing some Javascript code for an ASP.net page.
I have the string "foo" assigned to a string variable myString.
I would like to assign the value of myString to a JavaScript variable, so I write in my ASP.net code:
<script type='txt/javascript' language='javascript'>
var stringFromDotNet = '<%=myString%>';
</script>
This works fine as long as myString does not contain quotation marks or line-breaks, but as as soon as I try to assign something with quotation marks or line-breaks, all hell breaks loose and my code doesn't work. As a matter of fact, I can see that this code is vulnerable to all sort of injection attacks.
So... What can I do get the value of myString assigned to a variable in JavaScript?
Update: I've tried creating a page with just an ASP:Hidden field. It looks like the values inside are html encoded.
You could use JavaScriptSerializer and that's guaranteed to be safe against XSS:
<script type="text/javascript">
var stringFromDotNet = <%= new JavaScriptSerializer().Serialize(myString) %>;
</script>
This approach also allows you to pass complex objects and not just plain strings:
<script type="text/javascript">
var complexObjectFromDotNet = <%= new JavaScriptSerializer().Serialize(new { id = 123, name = "foo\"' <bar>" }) %>;
alert(complexObjectFromDotNet.name);
</script>
I think this may be the answer are looking for: http://www.velocityreviews.com/forums/t70655-escape-function-in-asp-net.html#edit352659. Basically, encode the value on the server side and unencode it with JavaScript:
var stringFromDotNet = decodeURI(<%=Server.URLEncode(myString)%>);
This will ensure that quotes and other dangerous characters won't break your script, or open up attack vectors.
You could either assign the js variable using double quotes like so
var stringFromDotNet = "<%=myString%>";
Or you could escape the single quotes and replace line breaks with literal "\r\n" in your string in the server side.

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