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

1
  • I've never used jQuery Cookie, but it sounds like things aren't getting JSON encoded/decoded. Try setting $.cookie.json = true;. Commented Apr 12, 2013 at 17:44

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

@Charles, which one did you use?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.