4

Using Ruby on Rails 5.0.3 .

I want to set some value in cookie using JavaScript (when button clicked), and get it in Rails.

I know how to access session in Rails, which is session[:some_key] or cookies.

But I don't know how to do in JavaScript. (it must be able to accessed from Rails session or cookies.)

How can I do it in JS?

Or any other ways to save some value in JS, and get it later in Rails ?

5
  • 1
    JS runs on the client and therefore is not able to directly affect the session, which is stored on the server. You could send an AJAX request from JS to the server which gets/sets the session values you require, though. Commented Mar 21, 2018 at 15:39
  • You'll need to make a server request from the client: take a look at XmlHttpRequest. Commented Mar 21, 2018 at 15:40
  • Okay, then I can use cookie? Anyway I want to save some value in JS, and get it later in Rails... Commented Mar 21, 2018 at 15:45
  • I want do it without sending request if I can. Commented Mar 21, 2018 at 15:48
  • why you don't you use browser cookies that you can access or set both from rails and from client side cookies[:key] in Rails and document.cookie to get the cookie list in Client Side. Commented Mar 21, 2018 at 16:18

2 Answers 2

4

Unfortunately, you can't modify Rails session from the client side, even if it stored in cookies. Because the rails session is encrypted. As a solution, you can use regular cookies, not the Rails session.

Check http://api.rubyonrails.org/v5.1/classes/ActionDispatch/Cookies.html https://www.w3schools.com/js/js_cookies.asp for more information.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! so Rails cookies does not get encrypted?
Yes, cookies are not encrypted and open for read and modification from the client side. The session is also cookies, in most cases, lets forget about the AR session storage, but all the data that are stored in Rails session are encrypted so without secret_key_base you can't modify or read this data from the client.
Can't you just set the cookie and send the value via ajax at the same time you click the button?
1

The cookie for the rails app is just some hashed string to ID the server cookie, which has the data.

What they said, use Ajax to some controller method you write to update your necessary info into the rails cookie.

Comments

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.