5

I have created Ruby Session Variable I need to access this variable in Javascript

Lets take this scenario

session[:note] = 'Some Notes' this is done in Ruby on Rails

Now I want to access this is like

var session_val = js-code for access above session variable.

its not js.erb I know if it is js.erb we can access like

var sesion_val = "<%= session[:note] %>"

TIA

2 Answers 2

5

You can use HTML5 data method from where you can access the variable.

suppose, your JS function is calling from a button. thus, you can define that button as:

<button class="btn" data-session="<%= session[:note]%>" onclick="seesionCheck()">Hello</button>

now, in your JS function you can access the variable as:

$(".btn").data('session');
Sign up to request clarification or add additional context in comments.

2 Comments

If you only use this single variable then HTML DOM size will be not that increasing as you thought.
@Veeru, So it is supposed to be the accepted answer, right?
3

The session is on serverside. Your JS is on clientside. There is no way to directly read the session from JS. There are two ways you can get around it:

  • Seed the values when you render your views. As you said, you can put it in your ERb. However, a better approach is using JSON:

    var session_val = <%= session[:note].to_json %>
    

    This avoids possible issues with escaping (or with lack thereof).

  • Ask the server via AJAX

2 Comments

Rails's session is just browser cookies right? How is it server-side?
@LirenYeo: Rails has cookie sessions by default, but you can use another session_store. Cookies are limited to 4Kb, may pose a security leak depending on your usage, and they increase the communication overhead; their advantage is that the server doesn't need to store things, so they slightly speed up things serverside by slightly increasing communication costs. While cookies are available at clientside, they are typically considered "server stuff", and not messed with clientside. (Though I should probably have tempered the "no way" in my answer.)

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.