简体   繁体   中英

jQuery Cookie plugin doesn't really seem to be setting a cookie

My code sets a cookie with javascript (using the cookie plugin for jQuery), then makes an ajax call to a php script that needs to read that cookie. It appears that the jQuery cookie plugin has a bug, because the PHP script isn't able to read this cookie. Furthermore, when I look in the Resources panel of Chrome, I don't see the cookie under the relevant domain. Additionally, if I set the cookie using the standard document.cookie method of Javascript, the cookie DOES appear in the Resources panel and my PHP script is able to read it. The main reason I want to use the jQuery plugin is because the cookie value I'm setting has line breaks, and the jQuery cookie plugin seems to handle that elegantly. It's a value that is going to be stored in a MySQL database, and those line breaks will be automatically converted to (br) and (p) tags when output. So the jQuery cookie plugin seems to give me the value I want... but not in a real cookie!

Anyway, here's the code I'm using. Feel free to just tell me how to maintain the linebreaks I need without using the jQuery cookie plugin rather than trying to figure out what's going wrong with the plugin/my implementation of the plugin.

Javascript:

$.cookie('flavor','chocolate',{expires:7});
$.get('http://example.com/readCookie.php',function(data){
    console.log(data);
});

readCookie.php

$myCookie = $_COOKIE['flavor'];
echo $myCookie;

The 'echo' statement above doesn't echo anything at all, not even an empty string. If I try var_dump with the cookie, I get NULL. I can, however, enter $.cookie('flavor') into the console and see that it was in fact set. But as I said before, it doesn't appear in the Resources panel of Chrome's developer tools, so I'm not convinced that it is actually a real cookie... and my PHP script seems to agree with that doubt as well :)

In the code you posted, you set a cookie named 'flavor' on the client side, and try to read a cookie named 'comment' at the server. Makes sense to me that you're not getting anything.

Perhaps that's just an error on your part in posting the question.

So what happens when you point the AJAX request at

'http://' + window.location.host + '/readCookie.php'

Or even at just

'/readCookie.php'

Cookies are domain specific.

I suspect the line breaks in the cookie value may well be causing the problems.

Why not base64 encode the cookie value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM