Access Session variables in JavaScript - javascript

I wanted to access a session variable in javascript in asp.net mvc application. I have found a way to do it in aspx view engine but not in razor.
Please tell me a way to access the session variables

You can do it this way for a String variable:
<script type="text/javascript">
var someSessionVariable = '#Session["SomeSessionVariable"]';
</script>
Or like this if it's numeric:
<script type="text/javascript">
var someSessionVariable = #Session["SomeSessionVariable"];
</script>
This is really not a very clean approach though, and requires inline JavaScript rather than using script files. Be careful not to get carried away with this.

I personally like the data attribute pattern.
In your Razor code:
<div id="myDiv" data-value="#Request.RequestContext.HttpContext.Session["someKey"]"></div>
In your javascript:
var value = $("#myDiv").data('value');

In my asp.net I am not getting the result by
<script type="text/javascript">
var someSessionVariable = '#Session["SomeSessionVariable"]';
</script>
But I get the answer by below code,
<script type="text/javascript">
var yourVariable = '<%= Session["SessionKey"] %>';
</script>

For google searchers,
In addition, If you want to access the session variable in external .js file you can simply do like this,
------ SOME HTML PAGE ------
//Scripts below Html page
<script>
//Variable you want to access
var mySessionVariable = '#Session["mySessionVariable"]';
</script>
// Load External Javascript file
<script src="~/scripts/MyScripts/NewFile.js"></script>
Inside NewFile.js
$(document).ready(function () {
alert(mySessionVariable);
});

Related

How to use Javascript file as a resources file

I'm trying to make a Javascript a key value object and use it as my Resources for localization
I have made this Jascsript code in a javascript file:
var Values = {
lbl_CustomerName:"Customer name: "
}
now need to use this object in my HTML file:
<title>Title</title>
<script src="../content/JS/Resources/en-us/Resources.js"></script>
</head>
<body>
Values.lbl_CustomerName
</body>
</html>
but it's parsed as a plane text!
I need to call this Object and access the key to show it's value in my HTML file how to do this?
we can truly advice you to use a javascript framework like angular js that embed this kind of behavior inside the framework.
without javascript framework, you will need to modify the DOM by yourself to insert your expected value. If you want to do it in pure javascript function you can write a functio like :
function insertKey(elem,id) {
elem.innerHTML = Values[id];
}
In your case it will look like that :
<title>Title</title>
<script src="../content/JS/Resources/en-us/Resources.js"></script>
<script type="text/javascript">
function insertKey(elem,id) {
elem.innerHTML = Values[id];
}
</script>
</head>
<body>
<div onload="insertKey(this,'lbl_CustomerName')"></div>
</body>
</html>
Whenever you want to parse a JavaScript code, you should wrap it inside a script tag.
<title>Title</title>
<script src="../content/JS/Resources/en-us/Resources.js"></script>
</head>
<body>
<script> document.write(Values.lbl_CustomerName); </script>
</body>
</html>
Browsers have interpreters and virtual machines. Natively, they parse the codes as HTML. if you need to use other syntaxes like CSS and JavaScript, you should tell them hey browser, parse this section as a CSS, JavaScript.
That's why we need and tags
I got the answer, the Javascript file must return an object, so I can use it on my page as follows:
javascript:
function resourcesObject() {
return {
"customerName": "Customer name";
};
}
HTML
<script>
var resources=resourcesObject();
var customerName=resources["customerName"];
</script>

Access object from script tag

I'm writing java script code in script tag in head like:
<head>
<script language="javascript">
object o = new object({....});
</script>
</head>
and trying to use object a in body tag
<body>
<script>
alert(o.value);
</script>
</body>
how can i access object from body???
is their any alternatives?
<head>
<script language="javascript">
var o = new Object();
o.value="a"
</script>
</head>
<body>
<script>
$(document).ready(function()
{
alert(o.value)
});
</script>
</body>
In this case var a is accessible in complete application, but one thing you need to make sure if you are using external JS files then it must be loaded when you using the variable. try onload function to assure JS is loaded and ready to use in body:
window.onload = function ()
{
alert(a);
}
Since your variable is declared outside any functions it can be accessed from anywhere in your document from the same script block or from a seperate script block like in your example. it can even be accessed from html event-attributes like this (note that its better to attach events to html elements using using js):
<button onclick="alert(a);">Click this button to open an alert!</button>

how to pass value to a js file

I know this question are asked hundreds of times :( but I just want to learn more :).
My question is simple, can I pass a value to a js file like this, if not, how ?
<script type="text/javascript" src="./js/create.js?method=create"></script>
Yes, you notice that I have a parameter method=create which I want to use in my create.js.
I know in jquery ajax, we have an easy way, but you must notice that the ajax method is in included in the js file, how could I pass a parameter to the js file itself ?
Any answer is welcome :)
Thanks.
This works perfect for me:
<script src="js/script.js" id="myScript" data-url="my_variable"></script>
inside the script.js file:
var myUrl = document.getElementById("myScript").getAttribute( "data-url" );
"myUrl = my_variable" inside the code
you can use myUrl everywhere.
Not really, no. What you can do is this:
<script type="text/javascript">
var method = "create";
</script>
<script type="text/javascript" src="./js/create.js"></script>
Another way is to only define functions inside your javascript file, and then invoke after it has loaded.
<script type="text/javascript" src="./js/create.js"></script>
<script type="text/javascript">
runMyLoadedCode("create");
</script>
Third way is belying my first simplistic answer: access the script tag itself and parse it. You can see here how to access the tag that has loaded your script; take its src value and cut it up to locate your method=create.

Accessing variables in another script

I have a JS
function check(obj) {
for( i=0; i<obj.elements.length; i++){
if(obj.elements[i].type=="checkbox"&&obj.elements[i].checked){
if(confirm(onSubmitMessage)){
return true;
}
else{
return false;
}
}
}
alert(alertMessage);
return false;
}
It's called from jsp page like this:
<script src="/TestAppChanged/check.js" type="text/javascript">
var onSubmitMessage = '"<bean:message key="body.onsubmit.delete"/>"';
var alertMessage = '"<bean:message key="body.alert.delete"/>"';
</script>
...
<form action="MyAction" method="POST"
onsubmit="return check(this)">
The problem is in that it doesn't see these glabal variables: onSubmitMessage and alertMessage. I thought that the problem was in the way that these things are set and changed it's values to usual strings like "qwe" but it didn't work again. So script in it's body simply doesn't see these variables. And the question is how to get them from script?
The <script> tag is used either to load an external file, like <script src="path/to/file.js"></script> or to define JS code inside the tag, like:
<script type="text/javascript">
// Your JS code.
</script>
You can't have both on the same tag. Thus, split your code:
<script src="/TestAppChanged/check.js" type="text/javascript"></script>
<script type="text/javascript">
var onSubmitMessage = '"<bean:message key="body.onsubmit.delete"/>"';
var alertMessage = '"<bean:message key="body.alert.delete"/>"';
</script>
A block between <script src=""></script> parsed when the browser don't support javascript. You need another <script> block, and put in this your variables.
It doesn't see the globar variabes because you declare a source in the script tag.
You should remove the global variables and declare them before the code of the function, in the js page, and then simply include the page like this:
<script src="/TestAppChanged/check.js" type="text/javascript"></script>
You should have two script tags. One for the variables. And then another one below it, linking to your javascript file.
You can set contents in tag OR set the src attribute.
It should be:
<script type="text/javascript">
var onSubmitMessage = '"<bean:message key="body.onsubmit.delete"/>"';
var alertMessage = '"<bean:message key="body.alert.delete"/>"';
</script>
<script src="/TestAppChanged/check.js" type="text/javascript"></script>
Don't mix the src attribute and code within the tag. Use two tags.

Accesing variables declared in JAVASCRIPT in a different HTML FILE

I have two files screen.html and db_fun.js.I have declared a variable at just the beginning as follows:
db_fun.js
var name = "abc";
now i tried to access this variable in the screen.html file as follows
screen.html
<html>
<body>
<form name = "screen" action = "db_fun.js">
<p> <script>document.write(name);</script> </p>
</form>
</body>
<script src="db_fun.js" type="text/javascript" />
</html>
it doesn't print nethn. Y so?
add this to the head
<script type="text/javascript" src="db_fun.js"></script>
I think that you should move
<script src="db_fun.js" type="text/javascript" />
In the head of the page. I.e. before document.write.
Because in the moment where you are trying to print 'name', the variable is still not created. Also I think that it is not a very good practice to use document.write to add content to your page. Try using jQuery or some other library. For example:
$(document).ready(function() {
$("p").html(name);
});
That's because you are inserting your JavaScript in the page footer. You have to firstly load your javascript file into your web site (in the head section for example) and then use your variable.

Categories