简体   繁体   中英

unable to set cookie after ajax request

I'm trying to set cookie with js-cookie.js after some ajax requests are done. If i put

Cookies.set('cookieName',object)
var cookie = Cookies.get('cookieName')
console.log(cookie);

inside success i get undefined, but if i put it outside of ajax callback i get printout (of course this is not what i want since this is finished before callback is done).

I tried also using $.whenAll() function ( https://gist.github.com/fearphage/4341799 ) to wait for all ajax request to finish but again inside callback function cookie is not set.

Do you use Codeigniter? I just solved same problem, in my case set a cookie in ajax and outside ajax had different results, like different url's.

I can't comment yet...that's why I'm posting here.

    $('form.login').submit(function(e) { 
        $form = $(this);
        e.preventDefault();
        $.get('someUrl')
        .done(function(data) { //data is returned async
            setCookie('weirdName', data, 1); //use async called data
        })
        .fail(function() {
            $('.error').show();
        });
    });

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM