ccleve
ccleve

Reputation: 15809

jQuery .ajax() won't set a cookie

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?

Upvotes: 2

Views: 4288

Answers (1)

ccleve
ccleve

Reputation: 15809

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.

Upvotes: 1

Related Questions