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();
%>
Related
I want to set a session variable in JavaScript and call page reload. And at this point I want the aspx.cs file to recognize the change in session variable and make appropriate changes to the webpage. I've tried using :
Assigning the ASP.NET Session Variable using Javascript:
function SetUserName()
{
var userName = "Shekhar Shete";
'<%Session["UserName"] = "' + userName + '"; %>';
alert('<%=Session["UserName"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetUserName()
{
var username = '<%= Session["UserName"] %>';
alert(username );
}
</script>
Although the session variable is set. And if I reload the page the JS field recognizes the new data for the session variable. It's not being recognized in the aspx.cs file.
Basically I'm trying to send data to my aspx.cs file based on user actions on the webpage.
Any help is greatly appreciated.
In the example you provide the ASP code (the code enclosed in <% %>) is processed before the page goes to the browser, the Javascript is processed a the browser.
If you want to pass back a value to the server there are a number of options, but one easy way would be to use a hidden input (example) inside a form, and submit back to server, and then when you get the post back on the server you add it to the session.
void Page_Load() {
//Don't blindly trust input from the client, validate first!
Session["Username"] = Request.Params["Username"];
}
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.
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.
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
I need help. I need to call a Java function "getLocCountByWhId()" in a Java class; this Java function is being called within a JavaScript in a for-loop. I need to pass in a JavaScript variable as a parameter into this Java function "getLocCountByWhId()". I have been struggling for a week and reading numerous website to get some guidelines but I have not been able to resolve the problem. Thank you in advance for your help. The code is listing below:
<script language="JavaScript">
<!--
function onCreatePO()
{
<%long jspAllocId = alloc.getId();%>;
var recItemId = ""; // Local variable for item id.
var recWhId = ""; // Local variable for warehouse id.
for (var i=0, j=document.what_if_summary.elements.length; i<j; i++)
{
var recStr = document.what_if_summary.elements[i].value;
var splitStr = new Array();
splitStr = recStr.split('^');
recItemId = splitStr[1]; // Get the field value for Item_ID.
recWhId = splitStr[2]; // Get the field value for Warehouse_ID.
// Get a database connection with global 'conn' object and retrieve store count.
<%AfsGetVDSCountByWarehouseBean.setConnection(conn);%>;
// The below assignment from JavaScript variable to JSP variable do not work
// because of a second JavaScript tag. How can I get around this ?
//<% String jspItemId = "<script>document.writeln(recItemId)</script>"; %>
//<% String jspWhId = "<script>document.writeln(recWhId)</script>"; %>
currentStoreCount = <%= AfsGetVDSCountByWarehouseBean.getLocCountByWhId(jspAllocId, jspItemId, jspWhId)%>;
}
}
//-->
</script>
// I get this example of assigning Javascript to JSP variable but I got double tag problem.
<script>
var v="Roseindia";
</script>
<% String st="<script>document.writeln(v)</script>";
out.println("value="+st); %>
What you are trying to do is not possible, and (sorry!) reflects a basic misunderstanding as to how server-side code such as JSP (or ASP, PHP, etc) works.
A JSP page is basically a Java servlet running on the web server that dynamically generates a web page and returns it to the browser. The resulting web page may contain HTML, CSS, JavaScript, etc., but to the Java code all of that is just text. The Java/JSP code cannot understand or interact with the JavaScript because the JavaScript doesn't run on the web server, it is just more text to be sent as part of the response back to the browser.
When the browser gets the response it will display the web page and execute any JavaScript.
Further reading (I wouldn't put too much faith in what you read at the RoseIndia site):
http://www.ibm.com/developerworks/java/tutorials/j-introjsp/
http://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html
http://java.sun.com/developer/onlineTraining/JSPIntro/