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

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)

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

Access MyBB PHP variable with Javascript

Is it possible to grab a MyBB PHP variable with Javascript? I am an userscript coder, and right now I use:
var uid = $("#panel").find('a').attr('href').replace(/[^0-9]/g, '');
To grab the user id (uid) of the current user. However, if I were to grab the UID from the user with PHP, it would look like this:
<?php echo {$mybb->user['uid']} ?>
Now to the actual question. Is it possible to grab the UID through Javascript, using the $mybb->user['uid']?
My answer is Yes, you can but it has some limits.
Well, if you remember in every headerinclude templates always have these code:
<script type="text/javascript">
<!--
var cookieDomain = "{$mybb->settings['cookiedomain']}";
var cookiePath = "{$mybb->settings['cookiepath']}";
var cookiePrefix = "{$mybb->settings['cookieprefix']}";
var deleteevent_confirm = "{$lang->deleteevent_confirm}";
var removeattach_confirm = "{$lang->removeattach_confirm}";
var loading_text = '{$lang->ajax_loading}';
var saving_changes = '{$lang->saving_changes}';
var use_xmlhttprequest = "{$mybb->settings['use_xmlhttprequest']}";
var my_post_key = "{$mybb->post_code}";
var imagepath = "{$theme['imgdir']}";
// -->
</script>
You can use MyBB's variables in any template with one condition: it's must be defined in the correlative PHP file. (Of course that variable must be inside the brackets { })
For example, the correlative PHP file with headerinclude template is global.php.
That's it. Have fun with MyBB :)
You can add a plugin to your forum. It is called template conditionals. Once you have that installed you can use the Mybb->user variable in all templates. There are many applications of this plugin, but for your code you can do:
<setvar uservar>$mybb->user['uid']</setvar>
var {$tplvars['uservar']} = $("#panel").find('a').attr('href').replace(/[^0-9]/g, '');
The plugin is on the MyBBHacks forum at the link below.
http://mybbhacks.zingaburga.com/showthread.php?tid=464
First, you will not be able to directly access a php server side variable in javascript, but there are several work arounds you could do.
The first one that comes to mind is to put this in your html page somewhere
<script type="text/javascript">
<?php echo "var uid = '". $mybb->user['uid']."';" ?>;
</script>
The downside to this is that this variable is now directly view able and editable in the DOM.
If you are using (or can use) a template you may place a PHP variable in a JavaScript variable defined within that template's content. If you plan to run this JavaScript on every page you must add the variable definition to the script block in the headerinclude template.
<script type="text/javascript">
<!--
var userID = {$mybb->user['uid']};
// -->
</script>
That example script will place the user's uid in the JavaScript variable userID.
Please note that <?php echo $mybb->user['uid']; ?> will not work as MyBB's template system does not allow PHP tags within it. You may instead use {$mybb->user['uid'} as an alternative.
Also, take note that if you are using a plugin and eval'ing the template in a function in your plugin file you will also need to globalise the PHP variable you are going to use.

How to update JavaScript variable using PHP

I have a JavaScript file named a pricing.js which contains this content in it:
var price_arr = new Array('$ 16.95','$ 30.95','$ 49.95','$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95');
But I want to to update this part of JavaScript file using PHP so please help me in this how can I update this part of the content from JavaScript file using PHP?
'$ 16.95','$ 30.95','$ 49.95','$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95'
Please understand that Javascript is Client Side code and PHP is server side code.
There can be 2 possible ways or scenarios which you want to achieve:
If you want to manipulate the JS file before sending it to client, you can rename the Javascript file to have .php extension and write php code to provide a variable. For Ex:
<?php
// write php code to create a string of values using a for loop
$price_array_string = "'$ 16.95','$ 30.95','$ 49.95',
'$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95'";
// Javscript Code var price_arr = new Array(`<?`php echo $price_array_string ?>);
The other alternative is that you get the value of price array by making an Ajax Request to a PHP web service.
Simply give the pricing.js file a .php extension. You can then include PHP in the javascript file the way you would for any other page. Just be sure your HTML code specifies that it's still "text/javascript" when you load it. You'll probably want to set the content-type in the PHP file as well, like so: header("Content-type: text/javascript");
Using your PHP script you can put a value in an HTML5 data attribute of an element on your page and then read it from your JavaScript, e.g. <body data-array="'$ 16.95','$ 30.95'"> can be generated with PHP, and then read with JS: var are = new Array($('body').attr('data-array').split(',')). Here jQuery is used in order to read the attribute value, but you can also do it with pure JavaScript.

Transferring javascript from a view to a seperate JS file

I am working on a legacy application and I want to move some JS code onto a separate JS file.
I will have to refractor some of the code to do this. I can put #Url.Content statements into data attributes in the HTML.
But how would I replace this line of code?
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
A separate JS file will not know what #Html.Raw means.
Server side code like that cannot run in a seperate javascript file. My solution for such problems is having a short javascript part in the head that runs on the onload event. There you can set variables that you can use in a seperate javascript file:
in the head:
array = #Html.Raw(Json.Encode(ViewBag.JobList));
in the seperate javascript file:
var array;
Then, in the seperate javascript file you can do with your array whatever is necessary.
The ViewBag.JobList data is only known at HTML page generation time. To include it in an external JavaScript file, you have to have another ASP.NET resource that recalculated ViewBag.JobList and then served as part of a dynamic JavaScript file. This is pretty inefficient.
Instead, do what you're doing with the URLs: pass the data through the DOM. If you're writing into normal DOM instead of a script block, you don't need the raw-output any more (*), normal HTML escaping is fine:
<script
id="do_stuff_script" src="do_stuff.js"
data-array="#Json.Encode(ViewBag.JobList)"
></script>
...
var array = $('#do_stuff_script').data('array');
// jQuery hack - equivalent to JSON.parse($('#do_stuff_script').attr('data-array'));
(Actually, the raw-output might have been a security bug, depending on what JSON encoder you're using and whether it chooses to escape </script to \u003C/script. Writing to HTML, with well-understood HTML-encoding requirements, is a good idea as it avoids problems like this too.)
I think you need to create action with JavaScriptResult
public ActionResult Test()
{
string script = "var textboxvalue=$('#name').val();";
return JavaScript(script);
}
But, before proceeding please go through following links
Beware of ASP.NET MVC JavaScriptResult
Working example for JavaScriptResult in asp.net mvc
I would also follow MelanciaUK's suggestion :
In your javascript file, put your code inside a function :
function MyViewRefactored( array ){
... your code ...
}
In your view, leave a minimal javascript bloc :
<script>
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
MyViewRefactored( array );
</script>

Using JavaScript Variables On Different Files

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.

Categories

Resources