6

I'm not able to access the variable in my .js file

the code i have at the top of the page is:

<script type="text/javascript">
    privilage = '<%=Session["privilage"]%>';
</script>

then i want to access privilage in my .js file.

i just want to alert this at the moment. would i be able to do this?

thanks

johnny 5
  • 19,893
  • 50
  • 121
  • 195
Ksnrg
  • 147
  • 1
  • 2
  • 9
  • 1
    What have you tried? If you put an alert(privilage) after privilage = '<%=Session["privilage"]%>'; will it display the correct value? – Tobias Nilsson Jan 08 '13 at 11:25
  • your code is correct, it works on my machine. I only used var privilage though .... – platon Jan 08 '13 at 11:32
  • i tried alert after declaring privilage = '<%=Session["privilage"]%>'; – Ksnrg Jan 08 '13 at 11:43
  • Your problem is that you're not running the code through the ASP.NET application server. JavaScript can only access what is sent to the browser, which does *not* include server-side session state. However, if you let the server process the <%= %> in your script before it is sent to the browser, the end result will be what you want. – Rytmis Jan 08 '13 at 12:17
  • Rythmis..Your correct .but,in my application the value is nedded without sending to the browser – Ksnrg Jan 08 '13 at 12:34

4 Answers4

2

Just use:

var privilage = '<%=Session["privilage"]%>';

or try:

alert(privilage);

It will display your Session value

lante
  • 7,192
  • 4
  • 37
  • 57
Renjith JR
  • 189
  • 1
  • 3
  • 14
2

You have to store session Value in HiddenField. After that You can Access the HiddneFieldValue in your JS

 <script type="text/javascript">
     document.getElementById('hdnField').value = '<%=Session["privilage"]%>';
 </script> 
johnny 5
  • 19,893
  • 50
  • 121
  • 195
Aarif Qureshi
  • 474
  • 1
  • 3
  • 13
0

use

<script type="text/javascript">
    var privilage = '<%=Session["privilage"]%>';
</script>
johnny 5
  • 19,893
  • 50
  • 121
  • 195
Elyor
  • 5,396
  • 8
  • 48
  • 76
0

I use it this way.

<asp:TextBox ID="txtValue" runat="server" CssClass="txtValue" style="display: none;" />

Then I use jQuery to access the value.

<script>
var txtValue = $(".txtValue").val();
</script>

Or even on a control.

<asp:LinkButton ID="lnkPrint" runat="server" CausesValidation="true"
CommandName="Print" CommandArgument='<%# Bind("PrintData") %>'
Text="<img src='/images/print_on.png' onmouseover='cursor: pointer;'
class='PrintButton' />" ToolTip="Print" OnClientClick="if ($('.txtValue').val()
!= '1') { $('.txtValue').val('1'); alert('Warning: Please enable pop-ups for
this site!'); }" />

This method survives ajax and postbacks.

Cheers

m4f1050
  • 103
  • 1
  • 9