0

So I'm new to jQuery and JSON but this is pretty straight forward and the fact the it isn't working is frustrating me.

I have an ASP.NET MVC Web site. I'm using AJAX (through jQuery) to load some data. Everything is well and good up until there.

I'm trying to store my result in a cookie by using carhartl / jquery-cookie.

The problem is when I try to store my data in a cookie the data isn't really stored. I'm using the code below:

                var jsonObj = JSON.stringify(result);

                jQuery.cookie("resultData", jsonObj, {
                    expires: 2,
                    path: "/",
                    json: true
                });

jQuery.cookie("resultData") returns null

I've tried running the same code but instead of my actual data I wrote "hello word" which worked just fine.

Can anyone help me please ?

Jonny
  • 2,787
  • 10
  • 40
  • 62
  • What's the size of your json ? You have a limit of 4K for each cookie, I think :) – Mihai Nov 08 '12 at 16:24
  • 7808 characters, is it the problem ? – Jonny Nov 08 '12 at 16:25
  • @Johny, see http://stackoverflow.com/questions/640938/what-is-the-maximum-size-of-a-web-browsers-cookies-key The overall length of the cookie should not exceed 4096 bytes.. – Gabriele Petrioli Nov 08 '12 at 16:27
  • As I said: 4KB. Try with a smaller json. Like { test : 1 } and see the result – Mihai Nov 08 '12 at 16:28
  • @Mihai and [at]Gaby aka G. Petrioli yep that's the problem ... lame. Thanks though if [at]Mihai puts this as an answer I can mark it as the correct answer :) – Jonny Nov 08 '12 at 16:36
  • If you don't need cookies why not use jStorage instead? http://www.jstorage.info/ – Martin Nov 08 '12 at 16:40

2 Answers2

2

The max size of a cookie is 4 KB. Check that :) Try with a smaller json, like { test : 1 } and see if that works

Mihai
  • 2,740
  • 31
  • 45
0

I guess the issue is that json: true is not an option, but it's the property of jQuery.cookie object itself.

So you should execute this line somewhere before your code:

jQuery.cookie.json = true;

and after that execute your code.

So, it could be something like that:

jQuery.cookie.json = true;

jQuery.cookie("resultData", jsonObj, {
    expires: 2,
    path: "/"
});

And note that, if you set $.cookie.json = true, you don't need to json-stringify your object - it would be provided automatically.

Please refer to official doc or answer on similar question here.

JanRe
  • 1
  • 1
  • 1