Reputation: 33381
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.
Upvotes: 51
Views: 164479
Reputation: 20768
The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!
For this to work you need to:
1) login with the ajax request from which you expect cookies to be returned:
$.ajax("https://example.com/v2/login", {
method: 'POST',
data: {login_id: user, password: password},
crossDomain: true,
success: login_success,
error: login_error
});
2) Connect with xhrFields: { withCredentials: true }
in the next ajax request(s) to use the credentials saved by the browser
$.ajax("https://example.com/v2/whatever", {
method: 'GET',
xhrFields: { withCredentials: true },
crossDomain: true,
success: whatever_success,
error: whatever_error
});
The browser takes care of these cookies for you even though they are not readable from the headers
nor the document.cookie
Upvotes: 55
Reputation: 173562
You're looking for a response header of Set-Cookie
:
xhr.getResponseHeader('Set-Cookie');
It won't work with HTTPOnly cookies though.
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.
Upvotes: 49
Reputation: 346
Similar to yebmouxing I could not the
xhr.getResponseHeader('Set-Cookie');
method to work. It would only return null even if I had set HTTPOnly to false on my server.
I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:
function getCookie(cookieName){
var cookieArray = document.cookie.split(';');
for(var i=0; i<cookieArray.length; i++){
var cookie = cookieArray[i];
while (cookie.charAt(0)==' '){
cookie = cookie.substring(1);
}
cookieHalves = cookie.split('=');
if(cookieHalves[0]== cookieName){
return cookieHalves[1];
}
}
return "";
}
Upvotes: 0
Reputation: 569
xhr.getResponseHeader('Set-Cookie');
It won't work for me.
I use this
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
success: function(output, status, xhr) {
alert(getCookie("MyCookie"));
},
http://www.w3schools.com/js/js_cookies.asp
Upvotes: 3