-1

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

4
  • because Session is not available in .js file. It can be access from your apsx page only. Commented Dec 27, 2013 at 13:30
  • This should help stackoverflow.com/questions/1343801/… Commented Dec 27, 2013 at 13:30
  • @Shahe actually you could write an HTTPHandler which will dynamically write the .js file Commented Dec 27, 2013 at 13:31
  • Use ajax request from js file to load session variable. Commented Dec 27, 2013 at 13:32

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

This is bad practice. Write that value into a JS variable instead to avoid polluting the DOM and the tree traversing to get the value.
why it is bad practice can you explain it
1

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)

1 Comment

Scripting language is aspx(Asp.net), already mention in question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.