2

I'm trying to set a browser cookie using a jQuery .ajax() call, and it's not working.

console.log("before cookies:" + document.cookie);
$.ajax({
    dataType: "json",
    contentType: "application/json",
    url: url,
    type: "GET",
    processData: false
}).then(function (data) {
    console.log("after cookies:" + document.cookie);
});

On the server side, the system adds a Set-Cookie to the response:

Access-Control-Allow-Headers    Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Origin *
Content-Length  63
Content-Type    application/json;charset=ISO-8859-1
Expires Thu, 01 Jan 1970 00:00:00 GMT
Set-Cookie  myApiKey=testkey;Expires=Wed, 20-Aug-2014 18:11:57 GMT;Max-Age=31536000

The output is empty:

before cookies:
after cookies:

Here's the rub. The main page is at one subdomain, and the ajax call is to another (api.mydomain.com). But I think I've set the CORS headers on the server side correctly. It should work.

Firebug does report that the cookie is set, but somehow it's not visible to the outer page. What's the trick?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
ccleve
  • 15,239
  • 27
  • 91
  • 157
  • 5
    It's likely that the Ajax call *does* set cookies, but it sets cookies for the *remote domain*, not your domain. – apsillers Aug 20 '13 at 18:25
  • 2
    Have you set the domain of the cookie to `.mydomain.com`? that will make it readable from any sub-domain – Jason Sperske Aug 20 '13 at 18:26
  • 2
    If setting the cookie's `Domain=.mydomain.com`, solves your problem, you have a duplicate of [Can subdomain.example.com set a cookie that can be read by example.com?](http://stackoverflow.com/questions/3089199/can-subdomain-example-com-set-a-cookie-that-can-be-read-by-example-com) (If it *doesn't* solve the problem, then Ajax may introduce some complexity and it might not be a duplicate.) – apsillers Aug 20 '13 at 18:32

1 Answers1

1

It turns out that this was a cookie domain problem, with a couple twists: the domain had a port number that had to be stripped, also, the server side in this setup didn't have access to the request hostname, only the ip address, which messed up other things.

Also, I tried to set cookies on the client side using javascript, but it turns out that client side security won't let you set cross domain cookies. CORS is only for the server side.

ccleve
  • 15,239
  • 27
  • 91
  • 157