简体   繁体   中英

Set cookie without page refresh

I am showing a jQuery overlay when users first visit a particular page

They have a radio button in the overlay that they can click to say they do not wish to see the notification again

I want to set a cookie that the user doesnt want to see the overlay again

Is it possible to set the cookie without refreshing the page?

I was going to make a ajax call back to the server and then set the cookie in the response headers but I guess they wont get set in an Ajax request/response?

Is it safe / OK to set the cookie purely from javascript? Or is that a bad idea?

any other options?

There is no reason that an AJAX call cannot set a cookie. It is basically just an HTTP request.

AJAX Requests Get And Set Cookies Like Any Other HTTP Request

You may use jQuery Cookie Plugin .

Some example:

function setCookieFilters() {
    var $filtersContent = $(".dynamic-filters");
    if ($filtersContent.length > 0) {
        if ($filtersContent.css("display") == "none") {
            $.cookie("isUsingFilters", "true", { expires: 7 });
        }
        else {
            $.cookie("isUsingFilters", "false", { expires: 7 });
        }
    }
}

you could also just get/set the cookie in plain old javascript: Create and Store a Cookie

Use this: this shall reload the page.

setcookie($data,$item_data, time()+ (3600));
echo "<script>location.href='index.php'</script>;

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