Hishalv Hishalv - 1 year ago 54
jQuery Question

How can i read cookies in rails that have been set by jquery

I am setting a cookie in jquery like this(works fine and the cookie is generated):

$(document).ready(function() {
var consp = $("input[home]").attr("home");
$("input[name='commit']").click(function() {
$.cookie('home', consp);

In my controller i am trying to get hold of that cookies value. So i am using standard READing of cookies like this

def some_method
@value = cookies[:home]

But when i output the value of @value, nothing is returned. This only happens if i set the cookie using jquery, however does not happen if i set the cookie directly through rails(no jquery). Any thoughts as to why this occurs? thanks

Answer Source

Ok, figured this one out:

I was creating this cookie when i was submitting a form and due to the mvc architecture, rails was submitting to a create action and the redirecting back to orginal page upon successfull redirect. So i needed this cookie to be valid across all pages so jquery.cookie plugin.

The solution was to pass the path parameter into the mix like this

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

This then allows the cookie to be read from all page routes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download