开发者

Setcookie won't work?

开发者 https://www.devze.com 2023-01-17 01:17 出处:网络
I set the cookies regularly in a callback page in my Twitter application. Everything works fine. Now, using jQuery, I submit a form, and the callback function activates a PHP script. That script only

I set the cookies regularly in a callback page in my Twitter application. Everything works fine.

Now, using jQuery, I submit a form, and the callback function activates a PHP script. That script only needs to set one cookie to the serialized values of $_POST; and the values run fine (both serialized and normal, I echoed them out to debug). The expiration time is set to 1 year ahead. But for some reason, the cookie just won't appear anywhere. Here's the code:

// js/main.js
$('#settings-form').live('submit', function() {
    $.post('controllers/settings.php', $(this).serialize(), function(data) { // Everything here works.
        if (data == 'OK') // no errors spits out "OK". this works
            changeView({'msg': 'Your settings were saved successfully.'}); // This just resets the view and adds a message div at the top. This works
        else
            changeView({'msg': data}); // This echoes the error if any exists. Doesn't happen,开发者_开发技巧 no errors arise
    });
    return false; // Cancels redirecting after submitting form
});
// controllers/settings.php
setcookie('user_settings', serialize($_POST), strtotime('+1 year'));

I checked all the variables and I even tried setting dummy ones for test (like "boo" instead of serialize($_POST). for some reason that doesn't work.

Any ideas why this is happening? I tried doing a chdir('..'); to make the cookie dir go to the right place, but that doesn't seem to be the problem, checking the cookies inside my browser doesn't seem to work at all, for any path. It just doesn't work at all. I also just tried manually changing the domain and path, but those don't work either.


Firstly, the chdir() thing is a red-herring -- Cookies are domain-specific; the directory path doesn't have any bearing on them.

Cookies can work a bit strangely when you're making ajax type calls, and I think this is what you're seeing -- The server is probably setting the cookie, but the browser may not be setting it in the cookies data it as it's not a page load.

I would suggest you'd be better off using PHP's session handling rather than cookies; it's better for security, less bandwidth (because the whole of the cookie data is transmitted in both directions with every http single request), and more likely to work.

If you really want to use cookies, it may work better if you use Javascript to do it. You can set cookies in your javascript code by accessing document.cookie. (you need to get the syntax right for the cookie string, but JQuery probably has its own functions that makes them easier to work with)

0

精彩评论

暂无评论...
验证码 换一张
取 消