Can an AJAX response set a cookie?

AjaxCookies

Ajax Problem Overview


Can an AJAX response set a cookie? If not, what is my alternative solution? Should I set it with Javascript or something similar?

Ajax Solutions


Solution 1 - Ajax

According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.

Quotation:

> If the user agent supports HTTP State Management it should persist, > discard and send cookies (as received in the Set-Cookie response > header, and sent in the Cookie header) as applicable.

Solution 2 - Ajax

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.

Solution 3 - Ajax

For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).

Solution 4 - Ajax

Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBillworth VandoryView Question on Stackoverflow
Solution 1 - AjaxStrelokView Answer on Stackoverflow
Solution 2 - Ajaxthis. __curious_geekView Answer on Stackoverflow
Solution 3 - AjaxBogdan StăncescuView Answer on Stackoverflow
Solution 4 - AjaxPhilView Answer on Stackoverflow