1

I try to set the Cookie in JavaScript. No cross-domain requests. I have a simple jQuery AJAX POST code:

console.log("before cookies:" + document.cookie);
$.ajax({
        url: "MYDOMAIN.COM",
        type: "POST",
        data: data,
        success: function (result, status, xhr) {
            var cookieSetData = xhr.getResponseHeader('Set-Cookie');
            var allHeader = xhr.getAllResponseHeaders();
            console.log("after cookies:" + document.cookie);
        }
});

Log result

before cookies:
after cookies:

Cookie I send from Server:

HttpCookie cookie = new HttpCookie("TempData");
cookie.Expires = DateTime.Now.AddMinutes(30);
cookie.Path = "/";
cookie.HttpOnly = false;
cookie.Value = somevalue;
ControllerContext.HttpContext.Response.SetCookie(cookie);

There is response headers from FireBag:

Set-Cookie: "TempData=AAEAAAD/////A…ul-2017 08:23:13 GMT; path=/"
Cache-Control: "private"
Content-Type: "text/html; charset=utf-8"
Content-Encoding: "gzip"
Vary: "Accept-Encoding"
Server: "Microsoft-IIS/10.0"
X-AspNetMvc-Version: "5.2"
x-aspnet-version: "4.0.30319"
X-SourceFiles: "=?UTF-8?B?RDpc0JDQvdC00YDQtdC…BwaW5nQ2FydFxBZGRUb0NhcnQ=?="
X-Powered-By: "ASP.NET"
Content-Length: "576"

But the xhr.getResponseHeader('Set-Cookie') return is null, and browser don't set cookie automatically (no cookies in log window). The xhr.getAllResponseHeaders() doesn't contain 'Set-Cookie'. Why?

What do I have to do to save cookie using jQuery.ajax?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Drew RS
  • 11
  • 2
  • https://stackoverflow.com/a/1460174/4228458 – CodingYoshi Jul 09 '17 at 08:38
  • you won't get the cookie-data from ajax response. see [here](https://stackoverflow.com/questions/12840410/how-to-get-a-cookie-from-an-ajax-response/37955635#37955635) – Mahbubur Rahman Jul 09 '17 at 09:16
  • @MahbuburRahman, A little part. If a cookie has the property `HttpOnly: true` then the cookie can not be readable from program. e.g `document.cookie`. Otherwise it can be readable. – Ataur Rahman Munna Jul 09 '17 at 09:44

0 Answers0