Using JavaScript Variables On Different Files - javascript

I have a js variable defined in a js file like so :
onlineUsers.js :
var _onlineUsers=new Array();
I'm then linking the js file into index.html like so
<script type="text/javascript" src="onlineUsersVars.js"></script>
and I know for sure it gets a value after awhile since I've checked it with alert .
However , when I try to do the same with another html file , e.g file2.html
then link the js file to get the same variable
file2.html :
<script type="text/javascript" src="onlineUsersVars.js"></script>
and check the value , the value is nothing .
Anyone has a clue what I'm missing ? Do javascript variables 'die' after being linked to one page ? How can I share the same global javascript variable between many html pages ?

You will have to include the script (onlineUsers.js) on every HTML page. And the variable (_onlineUsers) will need to be re-instantiated on every HTML page.

Yeah if you go from file1.html to file2.html, even though you have the same JS file on both files, the values will all clear. The best way to pass variables from page to page would be by using cookies.

Try using HTML5 localStorage to store the variable and then call it each time you need to.
function onlineUsers() {
var _onlineUsers=new Array();
localStorage.onlineUsers = _onlineUsers;
}
Then this value will be available anytime you need it. Although that is client side not server side.

Related

How can add value to vb variable in js code?

I'm try to add a value to my vb variable in my js code, this is my example
<script>
'<%Dim Myvariable As Integer%>' = 201278
</script>
but this doesn't work.
Is there a way to do this?
Declare variable either protected or public:
Protected test As Integer = 201278;
And in .aspx file:
<script>
<%=test.toString()%>
</script>
edit.
that comment doesn't make any sense #JoséGregorioCalderón the example shows that it IS in script tags. If you mean the file is an external JS file, that is a different problem.
You could solve this in two ways.
1) You serve the JS file as an ASPX file to generate parts of it that are dynamic. you'll need to take care of the headers to serve it is text/javascript
2) You write the variable to your HTML as a data attribute and read it into your JS directly.
i.e.
or...very quick pseudo code.
<body id="myBody" data-variable="<%=MyVariable%>">
var bodyElement = document.getElementById('myBody')
alert(bodyElement.dataset.variable);

Set Session value using Javascript and retrieving the same using razor umbraco

I have written following code let say in Page 1
<a Onclick="setSessionValue()" href="page2"></a>
<script type="text/javascript">
function setSessionValue()
{
var selectedCarNoideId = "1026";
'<%Session["BannerNoideID"] = "'+ selectedCarNoideId +'";%>'
alert('<%=Session["BannerNoideID"]%>');
}
</script>
And now retrieving session value on other page (Scripting File .chtml) using following code.
<h2>Session-:#Session["BannerNoideID"] </h2>;
In the Page 1 alert PopUp displays "1026" as session value
But In Page 2 tag display following value as a output of session .
"Session-:'+ selectedCarNoideId +'"
Am I missing any thing ?
You're mixing javascript and server-side code in such a way that the javascript isn't being evaluatd as you expect.
The Server side session variable is literally being set to '+ selectedCarNoideId +' as the page is being rendered. Javascript in this case is doing nothing to set the session value.
Although why you're getting the alert message to display 1026 is anyone's guess - is the BannerNoideID session variable being set elsewhere as well perhaps?
If you're trying to save a variable generated client-side with Javascript in the session on the server, you will need to submit it.
One way to do it would be to create a simple MVC Controller (WebAPI by default is sessionless) and then POST the value to it using Ajax or a form post.
Alternatively, you could pass the id through on the QueryString to the next page or something like that - that approach is probably the simplest.
Without knowing more about your setup, workflow and business logic I can't really suggest much more.

Accessing a local js variable in razor block

I am trying to write razor code inside javascript where I am trying to use a local variable inside the razor code. Here is the sample code:
<script type="text/javascript">
for (i = 0; i < data.result.length; i++) {
$("#member-table tbody").append("<tr>");
var id = data.result[i].MemberId;
var actions = $("<td>" + #Html.ActionLink("Detay", "Edit", new { id }) + "</td>)");
}
</script>
the problem is that id is not recognized by the razor code (i.e. it does not exist in the current context). How can I achieve that ? Is there any way ?
It's not possible to access a javascript variable in a razor block.
That's because razor is executed in the server, and javascript is executed in the browser.
However, by looking at your code it seems like you are using javascript to populate a table and that's bad, there are two patterns for solving this problem, one that solves everything in the server, and another one that solves everything in the browser.
Solving everything in the server:
If you decide that you want to solve everything in the server, your javascript should request the contents from the server and load them into a placeholder without changing them, something like:
$("#myButton").click(function(){
$("#myDinamicDiv").load("/Path/ToView");
});
and then you use razor's foreach loop to generate the table's html:
#foreach (var x in ViewBag.MyData)
{
<tr>
<td>Generate contents here, including links </td>
</tr>
}
Solving everything in the client:
As pointed out in another answer, if you are using the default routing, you can just create direct strings in the javascript code and add them to your page, keep in mind however, that when using this solution, as your page gets complex, your javascript will became less and less maintainable, having a for loop that iterates over data is a sign that maybe you can benefit from javascript UI frameworks like Angular.js and Knockout.js, in fact, what you are doing is the core of Knockout.js's third lesson in its tutorial (Single page applications)
If you're just using default routing, then simply just don't bother with the Razor #Html.ActionLink. Stick with an explicit tag:
var actions = $('<td>Detay</td>');
...obviously with whatever your current controller name is substituted for [your-controller-here].
(And I'm assuming your 'id' isn't necessarily URL-encoded, hence the 'escape'.)
You are mixing server side and client side here. You cannot create #Html.ActioLink using client side variables. Html.ActionLink is rendered on the server, it does not have any clue at all about your client side variables.
If you want to use a client side variable, like "id", render a plain html link (a) tag.
This worked for me once
if ('#ViewBag.DownloadLink' != '') {
window.location.href = '#ViewBag.DownloadLink';
}

A method to pass a variable to Javascript currently run in the header

Please excuse me ignorance, I'm completely new to Javascript.
I have this code that is currently run in the header, however I need to pass it $_GET variables before it runs.
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc');
jQuery('#mintpal-price').load('http://<site>/realtime/mintpal-realtime.php?symbol=ltc');
});
function refresh() {
setTimeout( function() {
jQuery('#bittrex-price').fadeOut('slow').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc').fadeIn('slow');
jQuery('#mintpal-price').fadeOut('slow').load('http://<site>/realtime/mintpal-realtime.php?symbol?ltc').fadeIn('slow');
refresh();
}, 10000);
}
It's pretty simple, all it does is pull the latest price from another PHP script.
I need to append a $_GET variable to the URL as current I have no way to change the ?symbol=ltc depending on which page the user is visiting. Because Wordpress is being awkward, I've had to save this function in a .js file and add a hook in functions.php otherwise it won't load at all. Ideally, I'd like to be able to run the function in the body so I can modify, but I can't get that to work either :/
I hope this makes sense, I'm open to any suggestions as I'm clearly missing the point somewhere here.
Thanks
You need to use the language that is building the web page to output some javascript for use in your functions.
Thus, if you're using PHP to build your page you could do something like this in the <head> section of your page:
<?php
print '<script>';
print 'var symbol = ' . $_GET['your_get_variable'] . ';';
print '</script>';
?>
Then, in your later javascript code you have your GET variable string stored in 'symbol' and can use it however you like.
The 'your_get_variable' is what is coming in via the query string in the URL that got you to the current page. Just make sure you put this code above where you want to use 'symbol' in your later javascript.
Also, It's not really a good idea to use $_GET data directly like that without some validation, but I'm just keeping the example clean.

How to access session variable from JavaScript file (.js) file?

I have to access session variable from javascript file
I am using below code to access from javascript,
var sessionValue = '<%=Session["username"]%>'
alert(sessionValue)
it is working well when the script function is placed inside the aspx page...but when I use the same code in .js file it is not working
I have seen all the related answers, nothing is useful for me, so don't mark it as duplicate
i think try to write your session value to a hidden html element and read value of this hidden element with javascript as follow :
<input type="hidden" id="session" value="'<%=Session["username"]%>'">
at your js:
var sessionValue =document.getElementById("session").value;
Depends on what is your scripting languauge in server side,
if it is JSP or PHP following should work.
var sessionValue = "'"+<%=Session["username"]%>+"'"
alert(sessionValue)

Categories

Resources