0

I used jQuery to create a cookie album_like that store an array of id, I would like to add/push new value to this array when some condition met, below is my code

if (typeof $.cookie('album_like') == 'undefined') {
    $.cookie('album_like', [data.album_id], { expires: 365, path: '/' });
} else {
    var arr = [$.cookie('album_like')];
    if (!($.inArray(data.album_id, arr) > 0)) {
        arr.push(data.album_id);
        $.cookie('album_like', arr);
    }
}

I found that the array become ["1, 2, 3, 4, 5"] when I use firebug to check the value, so the code !($.inArray(data.album_id, arr) > 0) not work, I think the array should be [1, 2, 3, 4, 5].

Anyone could give some advice on my code?

Thanks

Charles Yeung
  • 38,347
  • 30
  • 90
  • 130
  • I've never used jQuery Cookie, but it sounds like things aren't getting JSON encoded/decoded. Try setting `$.cookie.json = true;`. – The Maniac Apr 12 '13 at 17:44

1 Answers1

3

This is getting you a string as an array entry not an array.

 var arr = [$.cookie('album_like')];

Try this:

var arr = $.cookie('album_like').split(', '); // split string to array
$.each(arr, function(i,v){
    arr[i] = parseInt(v); // convert string array entries to ints
});

Or you could use json encoding to store and retrieve the array jquery save json data object in cookie

 $.cookie.json = true;
Community
  • 1
  • 1
Fresheyeball
  • 29,567
  • 20
  • 102
  • 164