How to get cookies from Ajax / xmlhttprequest call's response

3.6k Views Asked by At

My application is making a network call using xmlHttpRequest. In the response i am getting Set-Cookie header (verified with fiddler). I need to access these cookies from javasript. I tried with XmlHttpRequest.getAllResponseHeaders(), it is returning all headers except Set-Cookie.

Is there a way to access these cookies from javascript? If yes, please provide some example.

My application is running on Webbrowser control (IE10), Windows Phone 8.

Thanks in advance.

2

There are 2 best solutions below

0
On

While awaiting a more specific answer, you can instead send all the cookies set from the server through a post response, then set it locally, as so (using jQuery to make it easier):

// Client
var cookie;
$.post('example.com',{'stuff':'data'},function(data){
    cookie = data;
});

// Server
if(isset($_POST['stuff'])) echo WhateverTheCookieWouldBe;
0
On

Actually cookies can be accessed via

document.cookie // this will return a string contains all cookie values separated by semicolon

This is actually not true since because of the async nature of request

// Client
var cookie;
$.post('example.com',{'stuff':'data'},function(data){
    cookie = data; 
});

alert(cookie); // undefined