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?
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.
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.
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.
More generally, cookies are not required for AJAX. XmlHttpRequest support (or even iframe remoting, on older browsers) is all that is technically required.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With