8

I am using popular jquery Cookie plugin https://github.com/carhartl/jquery-cookie Wonder how to set and read a cookie with multiple values? Or maybe it's possible to add/remove values for that cookie?

$.cookie("MyTestCookie", email, { expires: 10 });

I want to add username to the same cookie

Update: just an example in .Net Storing multiple values in cookies

Community
  • 1
  • 1
Stewie Griffin
  • 9,257
  • 22
  • 70
  • 97

4 Answers4

19

If you want to set a cookie that has multiple values or "subkeys" and have them readable from .NET, you need to store the subkey as name-value pairs formatted like a querystring. You can use the jQuery.param() method to convert a Javascript object into a querystring.

var obj = { email: 'jdoe@example.com', username: 'jdoe' };
$.cookie("MyTestCookie", $.param(obj), { expires: 10 });

Then on the server, you can access the values as:

var email = Request.Cookies["MyTestCookie"]["email"];
var username = Request.Cookies["MyTestCookie"]["username"];

EDIT: I created a test page to show reading/writing multi-value cookies both on the server and client. http://www.systemex.net/Cookies/

NOTES:

  • You need to take care of escaping and unescaping the subkeys. This way any embedded = and & are handled correctly
  • When reading and writing jquery cookies, use option { raw: true } so it doesn't double escape.
  • I wrote a $.deparam function that will convert a name=value&name2=value2 string into a javascript object { name: value, name2: value2 }
  • One last thing, the jquery cookie plugin does not overwrite a cookie with the same name, it simply appends it to the current cookie collection. At this point, it would probably be better to rewrite the plugin to support subkeys and modifying existing cookies.

Anyway hope this helps.

Here is Default.aspx

<h1>Get Cookie From Server:</h1>
<ul>
<li>Email: <%= GetCookie("MyTestCookie", "email")%></li>
<li>Username: <%= GetCookie("MyTestCookie", "username")%></li>
</ul>
<h1>Get Cookie From Client:</h1>
<ul>
<li>Email: <span class="cookie" data-name="MyTestCookie" data-key="email" /></li>
<li>Username: <span class="cookie" data-name="MyTestCookie" data-key="username" /></li>
<li>Raw: <span id="raw" /></li>
</ul>
<h1>Set Cookie From Client:</h1>
<ul>
<li>Email: <input type="text" name="email" value="" /></li>
<li>Username: <input type="text" name="username" value="" /></li>
</ul>
<input type="submit" value="Submit" />

<script>

    $(function () {
        $(".cookie").each(function (index) {
            var name = $(this).data('name');
            var key = $(this).data('key');
            var cookie = $.deparam($.cookie(name, { raw: true }));

            $(this).html(cookie[key]);
        });
        $('#raw').text(escape($.cookie("MyTestCookie"), { raw: true }));


        $("form").submit(function () {
            var o = {};
            o.email = $('input[name=email]').val();
            o.username = $('input[name=username]').val();
            var value = $.param(o);
            var cookie = $.cookie('MyTestCookie', value, { raw: true });
            return true;
        });
    });

    jQuery.deparam = function (params) {
        var o = {};
        if (!params) return o;
        var a = params.split('&');
        for (var i = 0; i < a.length; i++) {
            var pair = a[i].split('=');
            o[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
        }
        return o;
    }

</script>

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var cookie = new HttpCookie("MyTestCookie");
        cookie["email"] = HttpUtility.UrlEncode("jdoe@example.com");
        cookie["username"] = HttpUtility.UrlEncode("jdoe&123");
        Response.Cookies.Add(cookie);
    }
}

public string GetCookie(string name, string key)
{
    var cookie = Request.Cookies[name];
    return cookie != null ? HttpUtility.UrlDecode(cookie[key]) : "";
}
Kiliman
  • 18,460
  • 3
  • 39
  • 38
  • any idea why I get nulls as value when I try to read cookie? that's my cookie value: email%3Drrr%2540asc.om%26password%3Da8f5f167f44f4964e6c998dee827110c – Stewie Griffin Jun 21 '11 at 18:33
  • I tried both ways: string email = Request.Cookies["SolidDomain"] ["email"]; string password = Request.Cookies["SolidDomain"]["password"]; string email1 = Request.Cookies.Get("SolidDomain").Values.Get("email"); string password2 = Request.Cookies.Get("SolidDomain").Values.Get("password"); – Stewie Griffin Jun 21 '11 at 18:36
  • I Use Json as cookie value instead. var data = JSON.parse($.cookie('cookiename')); if (data == undefined || data == null) data = {}; data.font = 22; data.color = 'blue'; $.cookie('cookiename', JSON.stringify(data), { path: '/', expires: 365 }); – Rbacarin May 09 '12 at 19:50
  • @Rbacarin not sure why you down-voted me. The answer I gave was based on the fact that he was looking for a way to read multi-valued cookies in .NET. Since .NET natively supports cookies as name-value pairs, that is what the solution uses. JSON would be fine, but you only show the client side. The server will now need to parse the JSON data in order to retrieve the data. – Kiliman May 22 '12 at 12:00
4

Try this one: https://github.com/tantau-horia/jquery-SuperCookie

Quick Usage:

create - create cookie

check - check existance

verify - verify cookie value if JSON

check_index - verify if index exists in JSON

read_values - read cookie value as string

read_JSON - read cookie value as JSON object

read_value - read value of index stored in JSON object

replace_value - replace value from a specified index stored in JSON object

remove_value - remove value and index stored in JSON object

Just use:

$.super_cookie().create("name_of_the_cookie",name_field_1:"value1",name_field_2:"value2"});
$.super_cookie().read_value("name_of_the_cookie","name_field_1");
Community
  • 1
  • 1
4

Even though it's not advised you still can add multiple values to a cookie and do the processing yourself.

(This will reduce the amount of cookies kept in the browser but since modern browsers are designed to process huge loads of cookies it wouldn't do anything to the speed of loading)

You can add your value using a loop and separate them using a special character like '%' and you can process your string on any encryption method you prefer and save all as one single cookie.

var setofcookies = username + "%" + password + "%" + email;
$.cookie("MyTestCookie", setofcookies, { expires: 10 });

Later you can use the SPLIT function to get the code into proper array value:

var cookie = $.cookie('MyTestCookie')
var mycookies = cookie.split("%");
document.write(mycookies[0]);

This is the most appropriate method you can use to process cookies, other methods will slightly slow down the page.

Schahriar SaffarShargh
  • 1,971
  • 2
  • 16
  • 24
0

When I was using the

var obj = { a: 'test', b: 'best' };
$.cookie("MyCookie", $.param(obj), { expires: 10 });

I was getting this value in the cookie

a%3Dtest%26b%3Dbest

So to get something like

a=test&b=best

you need to add this line before $.cookie()

$.cookie.raw = true;
Matt
  • 327
  • 1
  • 6
  • 20