robins
robins

Reputation: 1668

How to get session data in .js file

In my application when the user is login the particular user id is stored in the session. I want to get this id in a js file.In this js file contain state provider,factory etc

js

  var sessionValue = "'"+<%=Session["userId"]%>+"'"
  alert(sessionValue)

But it is show some error(Unexpected)

Upvotes: 2

Views: 3230

Answers (3)

user1555320
user1555320

Reputation: 495

I think that the problem is that your webserver isn't evaluating as ASP .js files. You have three different way to get what you want

  • configure your webserver so that .js files are treated as ASP pages, but noone would ever do that, it would add overhead over your
    code.
  • Render your js starting from a .asp page placing in your html something like: < script src="mysite/getjavascript.asp" >
  • Load session values with an ajax calls

Remember to print proper headers before printing your javascript

Upvotes: 0

Abhijeet
Abhijeet

Reputation: 4309

1.You can assign session value to hidden field.

<input type="hidden" name="userId" id="userId" value="<%= Session["userId"] %>">
  1. Get hidden field value from javascript function.

function GetUserId()
{
    var userId = document.getElementById('userId').value;
    alert(userId);
}

Upvotes: 1

MANISH KUMAR CHOUDHARY
MANISH KUMAR CHOUDHARY

Reputation: 3492

You can use something like

<script type="text/javascript">
function GetUserId()
{

    var userId = '<%= Session["userId"] %>';
    alert(userId);
}
</script>

Upvotes: 0

Related Questions