Can I set a session variable in jQuery?
I need to store some data in the session from jQuery and I also want to retrieve that data via jQuery.
Is there anything like
$.getSession.set("var","value");
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Session is accessible at the server side. But if you want, you can access your session by writing a function, which for example invokes ajax request to your server and gets whatever you want.
EDIT:
I’ll show you this using ASP.NET MVC framework, as I like it much. For the other frameworks idea is the same – just ask server about session.
So, let it be like below at the server side – simple controller and 2 basic actions are written:
Firstly, you have to store something into the session, for example by invoking
Indexaction. Next, invoke theGetSessionValueaction to retrieve value previously stored. Unless you have disabled session for your application, or cookies in your browser, you should get correct value.How to get the value ? Just send ajax request:
You can write javascript function which will do synchronous request – which in fact can freeze your browser for some minor time (depends on your server time consumption used for some calculations, network infrastructure conditions etc.):
or an asynchronous version, which invokes a callback when done:
BTW: I’ve used json seriazlization, as it’s the approach I prefer while passing the objects to and from the server. Other thing – jQuery
doneevent will only be triggered on success. In case of some errors at the server side (ex: uncaught exception), request returns http 500 and event is not invoked.