4

Is it possible to store a User's Cookie or Session in Controller and Get the cookie by accessing it from JS or Jquery?

Srikanth Jeeva
  • 3,005
  • 4
  • 38
  • 58

1 Answers1

15

Session values are available on the server.

You can set them like this in your controller:

session[:user_name] = @user.name

If you want to access that value later in javascript, you'll probably want to do something like this in a view:

<%= javascript_tag do %>
  var userName = '<%= session[:user_name %>';
<% end %>

Cookies are managed by the browser, so accessed differently.

To set one in your controller:

cookies[:user_name] = @user.name

(You can also specify the path, expiration, etc. for the cookie using options.)

It can then be accessed using jQuery:

var userName = jQuery.cookie("user_name");

Note: you can also access the cookie using pure javascript (not jQuery) by parsing document.cookie, but it is much easier to let jQuery do it for you (if you're already using that library).

Ryan Hertz
  • 1,222
  • 8
  • 9
Eric S
  • 1,363
  • 1
  • 10
  • 20
  • When i do this, I'm getting $.cookie is not a function. Should i include any Js other than jquery? i'm using jquery.min.1.9.1 – Srikanth Jeeva Mar 12 '13 at 05:18
  • @Srikanth: try using it without the path hash (I've updated that line) in the response. – Eric S Mar 12 '13 at 14:01
  • Also, depending on what other JS libraries you have loaded, you should replace all your "$" calls with "jQuery". (Some libraries - "prototype" in particular use the "$" namespace too. For more info on that, see http://stackoverflow.com/questions/6746352/replace-dollar-sign-with-jquery ) – Eric S Mar 12 '13 at 14:03
  • No equal sign before `end` in `<%= javascript_tag do %> ... <%= end %>` http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-javascript_tag – Green Jun 02 '13 at 19:21
  • @Kote - I'm using the same.. Thanks :) – Srikanth Jeeva Jul 03 '13 at 05:57
  • 7
    **jquery cookie is deprecated**, use [js-cookie](https://github.com/js-cookie/js-cookie) instead – Phil Mar 10 '16 at 19:23