I am developing an application using jQuery that uses cookies. Right now, it is located at application.html
on my PC desktop.
However, I cannot store and retrieve a cookie. I had included jquery-1.7.1.min.js
, json2.js
, and jquery.cookie.js
in my HTML file in that order.
Here is how I am storing a cookie to last for 7 days:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7});
The global array people_obj_array
looks like
[
{
"name": "Adam",
"age": 1,
},
{
"name": "Bob",
"age": 2,
},
{
"name": "Cathy",
"age": 3,
},
]
When I test JSON encryption with alert(JSON.stringify(people_obj_array))
, it looks fine:
However, when I retrieve this cookie via:
alert($.cookie("people"));
before even refreshing the page, an alert pops up that reads "null." Shouldn't the text be the alert JSON string? Am I using the JQuery cookies library correctly?
Just to clarify, here is how I am testing:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7}); // store
alert($.cookie("people")); // attempt to retrieve
I have Firebug, and I am willing to do some Console tests.
Cookies can be set in the browser with the help of JavaScript or the jQuery. Here we will be seeing how to set cookies in the browser with the help of jQuery and how to remove them later on.
Cookies are usually set by a web-server using the response Set-Cookie HTTP-header. Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie HTTP-header.
JavaScript can create, read, and delete cookies with the document.
Explanation. Yes! JavaScript can also manipulate cookies using the cookie property of the Document object.
It's probably the fact the file is on your desktop that's causing the problem. Browsers normally behave by serving up cookies based on the domain they were received from and their path.
You may not be able to read the cookie immediately after setting it: Writing a cookie involves setting headers in a HTTP request and, likewise, reading them involves reading headers in a HTTP response.
Try hosting your page on a web-server and see if that works for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With