How to assign values from form to Javascript session variables - javascript

I am trying to create Javascript Session variables that will read information from one form and pass these variables to another form.
I can assign strings to these Session variables but i cannot assign values from Form elements to these variables
function SetUserName()
{
<% var text1= "Charles";%>
<%Session["UserName"] =text1;%>
var session_value='<%=Session["UserName"]%>';
}
</script>
This is the Javascript on the first page which works and on a button click i call another page where i can display this Session Variable.
function LoadUserName()
{
var username = '<%= Session["UserName"] %>';
alert(username);
}
This gets called on load of second page. How can i pass values from HTML elements to the Session Variable?
For Example Say i have a Text Box
<asp:TextBox ID="Address_Box" runat="server" TextMode="MultiLine"
MaxLength="200" ></asp:TextBox>
How can I send the text from this box to the session variable?

Your code:
var session_value='<%=Session["UserName"]%>';
does not "access the ASP.Net session from javascript".
With this code you do generate (during the processing of the request) some text that will be sent to the browser. This text contains the string that results from the expression Session["UserName"].
Once this text arrives at the browser it is interpreted as javascript. This javascript has no knowledge of any session values or the fact that it was (partly) generated.
You need to find some way to send data from the browser back to the server (using postback or ajax, for instance) before it can be stored in Session.

You would have to put this somewhere in your c# code.
Session["UserName"] = Address_Box.Text;
For a more complete answer I'd have to see more of your code. For a better solution you'd have to explain what you're trying to achieve

Related

How to set a session variable in JavaScript and access it in ASP.NET .cs file

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"];
}

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

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

How to access javascript variable in .net master page

I need to enable a script which is present in a .net master page, in only selected html pages that use this master page. can this be achieved by declaring a variable in javascript of html pages where I need this script and set the variable to some value, so that I can enable the scripts in master page only when variable is NotNullorEmpty? Does some one know if this works. If so how to get javascript variable in html, in to .net master page ?
There are 2 ways I can think of.
The first if to assign the variable to a hidden input field. Which can be accessed in the Request.Form.
html
<input type="hidden" value="your value" name="Hidden1" id="Hidden1"/>
javascript
document.getElementById('Hidden1').value = "an other value";
C#
var myValue = Request.Form["Hidden1"];
The second is saving the variable into a cookie which can be accessed in Request.Cookies.
var myValue = Response.Cookies["Cookie1"].Value;
The most flexible form of this that I have seen is to render a JSON object directly to the page as script (adding any other script you might need also), then making the javascript code fill in a hidden field with JSON data on form submit for the server to parse.
Here are the basic steps:
Create an empty hidden field for the server to read when the client submits, but send it to the client empty.
Create a string which is the script and JSON data you need to send to the client. (Use the JavaScriptSerializer .NET class.)
Fill a LiteralControl with the script tag and its contents. (This works well in the OnPreRender step, but you can do it elsewhere.)
Include JSON2.js (it's all over the web - get it from a trusted source)
Write javascript code to fill the hidden field on submit, using JSON2.stringify() to push any javascript object into that field.
On the server, you can again use JavaScriptSerializer to read the values from the submitted object.
What you are basically wanting to do is test for javascript.
There are a few ways to do this, but I would use both a server-side and client-side cookie.
In your global.asax's onbeginrequest, test for a server-side cookie of "js-test-s"
Cookie Exists, check for "js-test-c"
"js-test-c" Cookie Exists, JS enabled
"js-test-c" No Cookie, JS disabled
Cookie doesn't exist...
Set the "js-test-s" cookie
output a simple html document...
[html]
[head]
[meta refresh tag set to 1 second /]
[script to set "js-test-c" cookie, then force refresh /]
[/head]
[body][/body]
[html]
Browser will refresh the request with one or both cookies set.
WARNING: You may want to store the original request details, and redirect to another location in case cookies are disabled.
I might be not understanding the question correctly but as far as I can tell the easiest way to do this is by creating a property on the master page and then setting it on all pages that need to execute the script:
In Master page
public bool EnableScript
{
set
{
if (value == true)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "startup", "alert('test');", true);
}
}
}
In all pages that need to run javascript that use the current master page:
protected void Page_Load(object sender, EventArgs e)
{
this.Master.EnableScript = true;
}
If you have to output your JavaScript on every page, even on the once that don't execute it (why?) then just add it as a function and then inside your property add a code to call that function, and set your property to true on all pages that require JavaScript to execute.

Categories