How to set cookie value with AJAX request?

127,020

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);
});
Share:
127,020
Aadi
Author by

Aadi

I always thing positive, and thinking positive makes me more powerful and strong to achieve my target. And i would love to work with challenging situation and my positive attitude makes me always happy and enthusiastic.

Updated on July 09, 2022

Comments

  • Aadi
    Aadi almost 2 years

    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?

  • Tomáš Zato
    Tomáš Zato about 9 years
    And what if I want to, sort of, fake a cookie and send it without setting it? After all, cookie is just a header, c'mon! :)
  • Tommi
    Tommi about 9 years
    @TomášZato According to XHR specs you can't do it. (See point 5 Terminate these steps if header is a case-insensitive match ... Cookie ... The above headers are controlled by the user agent to let it control those aspects of transport. This guarantees data integrity to some extent.). I believe you still can fake a cookie by setting it before request and deleting on complete callback. I believe it's the most we can do in browser.
  • Tomáš Zato
    Tomáš Zato about 9 years
    I ctually just reminded myself that javascript is single threaded, so setting a cookie and deleting it afterwards will not have negative results on other scripts.