Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Cookie plugin - multiple values?

Tags:

jquery

cookies

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

like image 821
Stewie Griffin Avatar asked Jun 20 '11 20:06

Stewie Griffin


3 Answers

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: '[email protected]', 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("[email protected]");
        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]) : "";
}
like image 161
Kiliman Avatar answered Nov 19 '22 10:11

Kiliman


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.

like image 23
Schahriar SaffarShargh Avatar answered Nov 19 '22 08:11

Schahriar SaffarShargh


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");
like image 4
uzername_not_found Avatar answered Nov 19 '22 09:11

uzername_not_found