Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery cookie not actually set a cookie?

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:

JSON test

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.

like image 646
dangerChihuahua007 Avatar asked Jan 29 '12 19:01

dangerChihuahua007


People also ask

Can jQuery create cookie?

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.

Are cookies set automatically?

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.

Can we set cookie in JavaScript?

JavaScript can create, read, and delete cookies with the document.

Can you access cookie using JavaScript True or false?

Explanation. Yes! JavaScript can also manipulate cookies using the cookie property of the Document object.


1 Answers

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.

like image 187
Dave Watts Avatar answered Oct 22 '22 00:10

Dave Watts