views:

319

answers:

3

Can I call the server to set a new cookie with an AJAX request (that is, after the page has already loaded)?

For example, when a visitor hits a link, ajax would open a php file that sets a new cookie like this:

setcookie('cookiename', 'true', time()+3000, "/",'...');

But this is done after the html (the page containing the actual <a> tag pressed) was rendered. Is it nevertheless ok to set cookies in ajax? (maybe because the php file loaded is separate from the original html page).

A: 

Why not use javascript to edit cookies? Return the content of the cookie in JSON format and use javascript to store the values.

kgiannakakis
You can't set HTTPONLY cookies from JavaScript.
Sam Hasler
A: 

I've set cookies in the response to AJAX requests on my site and I haven't had any problems with it yet. (Although I haven't looked for problems.) It could be that some browsers don't set cookies when receiving them in an XmlHttpRequest but so far I've seen it work in IE, Chrome and Firefox.

Sam Hasler
A: 

You can have the server's response set a cookie, certainly. Remember that cookies are an HTTP thing, not an HTML thing; the fact that your original HTML file is already on the browser is irrelevant. Your ajax request is a separate HTTP request to the server, which (hopefully!) generates an HTTP response back to the browser; and that response can include a new Set-Cookie header.

I'm not a PHP person, you'll need to check that there are limitations in the PHP mechanism you're using for setting the cookie (I can't imagine there are). But fundamentally, no, there's no problem doing this. I've done it with both JSPs and classic ASP.

T.J. Crowder
Redirecting headers are also an HTTP thing, but trying to redirect the user from the server inside an ajax request would just result in different output sent to JS!
sombe