Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 458
Kees C. Bakker Avatar asked Oct 11 '12 13:10

Kees C. Bakker


People also ask

Can AJAX response set cookie?

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

Do AJAX requests send cookies?

Basically, ajax request as well as synchronous request sends your document cookies automatically.

How do I get the response header cookie?

Just set the Set-Cookie header in the response from the server side code. The browser should save it automatically. As a developer, you may be able to inspect the value of the cookies using "Developer Tools". And the same cookie will be sent in subsequent requests to the same domain, until the cookie expires.


1 Answers

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

like image 90
MrE Avatar answered Oct 04 '22 05:10

MrE