Jonny
Jonny

Reputation: 2927

jQuery.cookie not storing my JSON string

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 ?

Upvotes: 0

Views: 1740

Answers (2)

JanRe
JanRe

Reputation: 1

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.

Upvotes: 0

Mihai
Mihai

Reputation: 2760

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

Upvotes: 2

Related Questions