Getting empty string when accessing server variable in client side - javascript

Code:
I had set the SessionData(EmployeeID) = "12345" in server side and it first executes at page_load
Then, In client side
function getEmployeeId() {
return "<%# SessionData("EmployeeID")%>";
}
I am getting the empty string for the above code.
Also, I tried using = as "<%= SessionData("EmployeeID")%>";
but I am getting the error as "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
"
Suggest me a solution.

I resolved the issue by putting the script code inside the Body section. Previously, it was in the Head section.
I used the "<%= SessionData("EmployeeID")%>"; code to access the server variable. It was working fine.

Related

Javascript Value of Variable not updating in Servlet

I have simplified my Code to breakdown the Problem and to have a simple Example with a Timestamp for whats actually going wrong.
So please not be suprised why i do a AJAX call, this is for the real functionality of the Servlet.
Its a Servlet and the follwing code is part of a JSP page, im Working on JAVA 1.7 and a Tomcat 7. I run it in Firefox and Chrome.
My goal is to retrieve a value from a Java method and write it on the servlet page into the DIV "ContentCharts".
The Problem is that Javascript does not update the vaule of "zeit" and always writes the same Timestamp into the DIV-Container and on the Console
$(document).ready(function()
{
function ausgabe()
{
<%
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
String JZeit = df.format(now.getTime());
System.out.println("FKT ausgabe zeit:"+ JZeit);
%>
var zeit='<%=JZeit %>';
console.info('Zeit:', zeit);
document.getElementById('ContentCharts').innerHTML = zeit;
}
$("#subtab2").click(function()
{
$.ajax
(
{
url:'overview',
data:{dbname:this.className},
type:'get',
cache:false,
success:function(){ausgabe();},
error:function(){alert('error');}
}
);
}
}
To test this I write the value of the JAVA varible "Jzeit" into the Serverlogs and get this (Click to see the Picture) results when I click the buttons three times. As you can see in the Picture here I get the right Timestamps.
Now I have also post the Value of the JS varialbe "zeit" into the Firebug Console. And now i get the Wrong time Stamps (Click to see the Picture)
The Content in the DIV is refreshing but here is the same Problem like in the Console, its always the same Timestamp.
These are my thoughts and Questions:
Why has the JS variable the wrong value when its right in JAVA?
Is there any option to say JS that it has to update the variable?
Could it be that JS saves the answers of the JAVA code and does not run it anymore, but runs the upper JAVA Code Snippet because there is no direct connection betwen JS and JAVA, like a value allocation?
How can i fix my Problem?
If you need more Informations to help me please ask for it.
You're a bit confused about the ajax pattern.
Note that anything you write in <%= jsp tags %> will be rendered on the server, then sent to the client where it will never change. Therefore your ausgabe function will always return the same result when it is called. Subsequent calls to the function will not make repeated server requests, which is the behavior you're observing.
To fix this, the success function in your ajax call should take an argument which will be instantiated with the response from the server. The java code you've written in the jsp tags in the ausgabe function should be moved to the server and any variables you need should be returned from the overview endpoint. Then, the ausgabe function should be refactored to take an argument containing the server-calculated values, and update your page as desired.
Here is some reading on ajax requests:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://api.jquery.com/jquery.ajax/

How to combine javascript code with java inside a jsp?

I have this cezar.jsp file and the following code inside my head below.
I have a textarea and I want to pass the value as a parameter for a java function.
<head>
<%# page import="cpd.CezarBun" %>
<script>
<%
cpd.CezarBun cezar = new cpd.CezarBun();
//don`t know how to use scripplets here
String contentIn = document.getElementById('myTextArea').value;
cezar.criptare(contentIn); //takes a String parameter
%>
</scrupt>
</head>
For a JSP scriptlet be able to use a value typed in a form field, you will have to send that value to the server in some way, given the fact that your server side Java code has no acess to what happens inside your form fields until you send the values. This means that document.getElementById('myTextArea').value will not work inside a JSP scriptlet block.
You could post the form and then use something like request.getParameter("fieldName") inside your JSP scriptlet block.
There is something you need to understand about the java in JSP's. It doesn't exist as far as the client side is concerned. All of the java code in a JSP is translated to a regular servlet. As far as the client side is concerned it's dealing with a standard html page. The only way for you to get client information to the JSP is the same with any other servlet.

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();
%>

assign javascript variable to ruby variable

I am working on one script which has been called from the websocket . This page of code is of html.erb
It pass variable to the javascript, and from that javascript variable i want to assign it to ruby variable ,
Here is the code
function set_color(val1,val2)
{
<%background_color_id = %>
var obj_color_id = '<%=background_color_id ='+val2+'%>' ;
console.log(obj_color_id)
}
The result from console log is +val2+
If I pass var obj_color_id = '<%=background_color_id ='val2'%>' ;
The result from console log is val2
Please help me assign javascript variable to ruby variable
You cannot do this. Javascript runs Client side, Ruby runs Server side.
You can't do that. All values <%= are translated on server side and their values are send to client. There is no ruby on client side. You have to send request to your websocket or http server in order to pass some data to server.
Actually, if I understand your code (your question is not well phrased, unfortunately), the simple solution is:
1- Assign a value via server-side code:
function set_color(val1,val2)
{
var bkgdColorId = "<%= background_color_id %>";
var obj_color_id = bkgdColorId;
console.log(obj_color_id)
}
2- (Or,) Assign a value from client-side code:
function set_color(val1,val2)
{
/** pseudo-code **/
on-click-event: makeAjaxCallToServer(){
urlForWebService, { color: val2 }
}
}
Using some jQuery (if assigning to server from client-side event) would greatly facilitate this process.

how to assign a javascript variable to a jsp string variable?

i m doing a database project using mysql as the database and jsp for my frontend part along with javascript and ajax for interaction.
Now the problem is i need to assign a java script variable which is having a string to a jsp variable.
I did this using the following statement?
<% String str="document.write(s)"; %>
where "s" is already defined as
<script type="text/javascript">
var s="hello world";
<script>
but i m getting error in the assignment statement(which is shown in bold above) as incorrect syntax?
the error i m getting is-
check the manual that corresponds to your MySQL server version for the right syntax to use near '<script>document.write(s)</script>'
what is the error in this stmt or is there any other method in doing this assignment?
Can anyone help in doing this?
You cannot do this. The JSP statement is executed server-side, before the execution of the Javascript statement, that is executed client-side after the browser received the http response.
It is not clear your goal, but if you only need to display in the page the value of a javascript variable, you can use:
trivial javascript:
document.write(s);
targeting existing element:
document.getElementById('myElementId').innerHTML = s;
using jQuery:
$('#myElementId').html(s);
If i understand correctly you are trying to build and execute a sql query based on user input that is handled by javascript. As ADC said this can not be done since jsp is executed server side therefore before browser executes javascript. What you can do is create the sql query and pass this as a parameter a different jsp/servlet (or the same if you can handle this case) which will execute the query
In the first page where sql statement is constructed in variable s you should put something like this
<script>
var s = "hello world";
function createLink(){
document.getElementById('mylink').href= 'page2.jsp?statement='+s;
}
window.onload=createLink;
</script>
<a id="mylink" href=""/>Click to exexute query</a>
which create a link to you second page (page2.jsp) passing the statement as parameter.
Now in page2.jsp you should retreive the parameter value like
<% String statement = request.getParameter("statement") %>
and then execute your query.
Even better you should use a servlet instead of a jsp page to perform the query. You could read a tutorial for jsp/sevlets to see how this can be done
eg. http://www.laliluna.de/articles/posts/first-java-servlets-jsp-tutorial.html

Categories