Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookie value with AJAX request?

I want to set a cookie value on an AJAX request but the code below doesn't work.

$.ajax({     type: "GET",         url: "http://example.com",     cache: false,     setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",     crossDomain: true,     dataType: 'json',     success: function (data) {         alert(data);     }); 

How can I set cookies in the header?

like image 343
Aadi Avatar asked May 31 '13 07:05

Aadi


People also ask

Can I set cookie on AJAX request?

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.

How do I set cookies in a post request?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

Does AJAX need cookies?

We are required to set cookies with AJAX requests or in such a way that any AJAX request sends those cookies to the server. One thing to note here is that every AJAX request made to any remote server automatically sends all our cookies to that very server without us having to do anything.

Are Httponly cookies sent with AJAX?

More generally, cookies are not required for AJAX. XmlHttpRequest support (or even iframe remoting, on older browsers) is all that is technically required.


1 Answers

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",     url: "http://example.com", cache: false, // NO setCookies option available, set cookie to document //setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl", crossDomain: true, dataType: 'json', xhrFields: {     withCredentials: true }, success: function (data) {     alert(data); }); 
like image 143
Tommi Avatar answered Sep 29 '22 13:09

Tommi