0

Possible Duplicate:
how to store an array in jquery cookie?

How to store every content of an array in cookie in javascript and also i have to retrive all the term of an array? I tried but i am not able to retrive items back from cookie....

My code is below wat i tried

var myArray=["123","234","32"];
$.cookie('myCookie', escape(myArray), { expires: 1});
var s = unescape($.cookie('myCookie');
Community
  • 1
  • 1
Parekh Shah
  • 69
  • 2
  • 5
  • 9
  • [What have you tried?](http://www.whathaveyoutried.com/) Have you searched for a tutorial on cookies? – Cerbrus Jan 11 '13 at 10:05
  • Added the jQuery tag because it looks like that... and now we have a duplicate. It looks like you should just not use `escape` or `unescape`. – Felix Kling Jan 11 '13 at 10:11
  • Your code has a typo. Missing the last parentheses at `var s = unescape($.cookie('myCookie');` – Felipe Fonseca Jan 11 '13 at 10:13
  • I tried with removal of escape and unescape but didnt get the proper solution. I am able to save the array in cookie but how to retrive the every term that i am not able to do – Parekh Shah Jan 11 '13 at 10:14
  • If you are using this cookie implementation, it seems you have to set the `json` option to `true`: https://github.com/carhartl/jquery-cookie#json. – Felix Kling Jan 11 '13 at 10:25

2 Answers2

0

Using JQuery, you can use serialize function to retrieve all data in string : http://api.jquery.com/serialize/

sdespont
  • 13,915
  • 9
  • 56
  • 97
0

To create a cookie in JavaScript you must assign a string to document.cookie.

It takes values in a name = value format e.g.

document.cookie = 'data=hello; max-age=60; path=/; domain=yoursite.com';

The best way to store an array in here is to use JSON and the method JSON.stringify():

var arr = ['hello', 'goodbye', 'au revoir'];
document.cookie = 'data=' + escape(JSON.stringify(arr)) + '; max-age=60; path=/; domain=yoursite.com'

(Note a cookie must be <= 4KB)

Retrieving the cookie is a little harder as it is a string, so I borrowed this function which searches the string for your cookie name then returns it's value:

// Source: http://www.thesitewizard.com/javascripts/cookies.shtml

function get_cookie ( cookie_name )
{
    var cookie_string = document.cookie ;
    if (cookie_string.length != 0) {
        var cookie_value = cookie_string.match (
                        '(^|;)[\s]*' +
                        cookie_name +
                        '=([^;]*)' );
        return decodeURIComponent ( cookie_value[2] ) ;
    }
    return '' ;
}

In our example you would use it like this:

var cookie = get_cookie('data');
var arr = JSON.parse(cookie); // Convert JSON string back into array

Note I use JSON.parse() to convert the JSON string back into a JavaScript array.

For more information on utilising cookies in JavaScript I suggest you read: http://www.thesitewizard.com/javascripts/cookies.shtml

George Reith
  • 13,132
  • 18
  • 79
  • 148