Accessing a session variable using jQuery

I need to display an HTML element in rails, depending on whether the session variable is set or not. Is it possible to do something like this?

+4
source share
5 answers

The session is server-side, I'm not a rails developer, but in asp.net mvc I made an ajax call that gets the Session value and returns it to the client. Just an idea.

+3
source

You cannot access any side on the server side from the client side. You can basically display the value of the session variable in a javascript variable and use it on the client side in jquery.

+1
source

A small library to help you read cookies.

var cookieHelper = (function () { return { createCookie: function (name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; }, writeSessionCookie: function (cookieName, cookieValue) { document.cookie = cookieName + "=" + cookieValue + "; path=/"; }, readCookie: function (name) { var nameEq = name + "="; var ca = document.cookie.split(';'); var i; for (i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEq) === 0) { return c.substring(nameEq.length, c.length); } } return null; }, deleteCookie: function (name) { this.createCookie(name, null, -1); }, testSessionCookieEnabled : function() { document.cookie ="testSessionCookie=Enabled"; if (getCookieValue ("testSessionCookie")=="Enabled") return true else return false; } }; }()); 

Using:

 if(cookieHelper.testSessionCookieEnabled) { cookieHelper.writeSessionCookie("test","session"); } else { //do something } var cookieValue=cookieHelper.readCookie("test"); 
0
source

you can display the js representation in rails and put the session variable there. for mo info see http://railscasts.com/episodes/205-unobtrusive-javascript

0
source

If you use rails 3 and save your session variables using a cookie store, you should have access to session variables using JS just like accessing a typical cookie.

0
source

All Articles