Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to make a session value available to JavaScript?

When my page loads, it stores an id from the database into session: Session["AppId"] = 1234. However, when I am doing JavaScript stuff, I need to know that AppId for database calls. How can I make that available to my JS from the server code? Would registering a script tag with var appId = 1234 be the way to go or does that code smell a bit too ripe?

Would adding a custom-attribute to the body tag make more sense? data-appid=1234 for example?

I'm new to web stuff, so the do's and don't's aren't always obvious to me. If there's a right/best way, feel free to share it.

EDIT:

The solution I actually needed was HttpContext.Current.Session["AppId"]. I didn't think static methods could access session values, so I thought I had to store it in the mark-up to pass to my WebMethod through an Ajax call. I accepted the answer I did because it answered the question I asked. I just asked the wrong question. =) I'm new remember - go easy on me!

like image 284
Yatrix Avatar asked Feb 19 '23 06:02

Yatrix


1 Answers

There are many ways to do this:

  • As you posted, a data-* attribute
  • A hidden form field (if you have a form on the page)
  • Embed in the URL
  • Output to javascript into a variable

There is no consensus on which is best.

like image 88
Oded Avatar answered Feb 21 '23 19:02

Oded