Kees C. Bakker Kees C. Bakker - 5 months ago 137
jQuery Question

How to get a cookie from an AJAX response?

I have a

$.ajax
request on the same domain and I want to read the cookie. It keeps returning
null
.

$.ajax({
type: 'GET',
url: myUrl,
success: function(output, status, xhr) {
alert(xhr.getResponseHeader("MyCookie"));
},
cache: false
});


Any ideas? I'm using Chrome for this.

Answer

You're looking for a response header of Set-Cookie:

xhr.getResponseHeader('Set-Cookie');

It won't work with HTTPOnly cookies though.

Update

According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2, this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader(), so the only reason why this could work is basically a "naughty" browser.