Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threeway cookie

I'm building a popup with 3 buttons! Each button needs to set a cookie but with different expiry time/date. I'm using jquery.cookie for this!

  • 1 button is more a session cookie. So when clicking this button the popup needs to dissapear and shown again when I start a new browser screen. So NOT when I open a page in the same browser window and same website.

  • 1 button is for "Don't show popup again" which will set cookie to 7 days

  • 1 cookie is set in the AJAX succes function and is set to 365 days

I'm having trouble to get the different expiry times to set up correctly. So for example when I click the button with the session cookie then the popup shows again when I open a new page inside the website.

I can't see what I'm doing wrong! I don't get any console errors but the cookies just won't set properly.

What I have is this:

 $(document).ready(function(){


    var my_cookie = $.cookie('regNewsletter');

    if (!my_cookie) {
      setTimeout(function(){
        $('#newsletter').modal('show');
      }, 1000);
    }
    $(".close--btn").on("click", function () {
      $.cookie('regNewsletter', true, {
        path: '/',
        domain: ''
      });
    });
    $(".dismiss--btn").on("click", function () {
      $.cookie('regNewsletter', true, {
        path: '/',
        domain: '',
        expires: 7
      });
    });
    console.log(my_cookie);

 // code for removing cookie when session ends //
 window.onbeforeunload = function() {
    $.removeCookie('regNewsletter', { path: '/', domain: '' });
 };


 $("#newsletter .btn").click(function(e){
      e.preventDefault();

       $.ajax({
       ... 

        success: function(txt, status, xhr){
       // some code //

              $.cookie('regNewsletter', true, {
                path: '/',
                expires: 365
              });

        // etc etc //


  });
like image 686
Meules Avatar asked Jan 26 '16 18:01

Meules


4 Answers

To set a session cookie you don't need to delete it onbeforeunload, but just set a cookie with no expiry set. You also don't need to set the domain, if the default is OK, which is the domain of the current webpage.

live demo

$(document).ready(function(){
    var my_cookie = $.cookie('regNewsletter');        
    if (my_cookie && my_cookie=="true") {
      alert("Cookie found");
    } else {
      setTimeout(function(){
        //$('#newsletter').modal('show');
        alert("Popup newsletter");
      }, 1000);
    }
    $(".close--btn").on("click", function () {
      // set a session cookie. It'll be automatically deleted
      // when the browser is closed
      $.cookie('regNewsletter', 'true', {
        path: '/'
      });
      alert("session cookie set");
    });
    $(".dismiss--btn").on("click", function () {
      $.cookie('regNewsletter', 'true', {
        path: '/',
        expires: 7
      });
      alert("cookie set for 7 days");
    });
    console.log(my_cookie);
    $("#newsletter .btn").click(function(e){
       e.preventDefault();
       $.ajax({
         url:"setcookie.html",
         success: function(txt, status, xhr){
           $.cookie('regNewsletter', 'true', {
             path: '/',
             expires: 365
           });
           alert("cookie set for 365 days");
         }
       });
     });
 });

html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="jquery.cookie.js"></script>
<button class="close--btn">close</button>
<button class="dismiss--btn">dismiss</button>
<span id="newsletter"><button class="btn">ajax</button></span>
like image 136
Gavriel Avatar answered Oct 24 '22 05:10

Gavriel


Why do you have this piece of code?

// code for removing cookie when session ends //
window.onbeforeunload = function() {
   $.removeCookie('regNewsletter', { path: '/', domain: '' });
};

It is not clear from your question which circumstances are causing the problems you are seeing, but I suspect this is part, if not all, of them.

The point of a session cookie is that it will be deleted automatically when the browser closes. There is no need to manually remove it.

That piece of code will remove your cookie as soon as you close the tab, window, or navigate to another page though. So if you are doing any of those then reopening the page within the same browser session you will get the behaviour you are seeing, as the cookie no longer exists.

Obviously the 7 and 365 day expirations are also ignored for the same reason.

Remove the piece of code and the cookie should then persist for the appropriate length

like image 40
Rebecka Avatar answered Oct 24 '22 04:10

Rebecka


You can check your cookies using browser developer tools. In Google Chrome, it is F12 -> Resources at the top (of the newly opened frame), Cookies on the left.

I think the problem might be that you don't set the correct domain for these cookies.

Update: Another suspicious thing is that you remove the cookie on window unolad:

window.onbeforeunload = function() {
    $.removeCookie('regNewsletter', { path: '/', domain: '' });
};

You can set it to 7 or 365 days, but it gets removed on window unload, because you don't have 3 cookies here, it is the same cookie 'regNewsletter' which is configured with different parameters.

Each time you set it, it overwrites previous values (this is probably what you want). But it looks like you should not remove it.

Update 2: instead of removing it, try to just leave it without the expiration date, according to this question and answer it should be automatically cleared when users closes the browser. According to your description, it should be even better than removing it in onbeforeunload.

like image 2
Boris Serebrov Avatar answered Oct 24 '22 03:10

Boris Serebrov


Your code has only a few issues:

  • You can use the default value for the domain
  • You don't need the onbeforeunload method to remove the session cookie
  • There is no need to setup listeners if the cookie is present

var my_cookie = $.cookie('regNewsletter');

if (!my_cookie) {

  setTimeout(function() {
    $('#newsletter').modal('show');
  }, 1000);

  // 365 days cookie

  $("#newsletter .btn").click(function(e) {
    e.preventDefault();
    $.cookie('regNewsletter', true, {
      path: '/',
      expires: 365
    });
  });

  // Session cookie

  $(".close--btn").on("click", function() {
    $.cookie('regNewsletter', true, {
      path: '/'
    });
  });

  // 7 days cookie

  $(".dismiss--btn").on("click", function() {
    $.cookie('regNewsletter', true, {
      path: '/',
      expires: 7
    });
  });
}
like image 1
R.Costa Avatar answered Oct 24 '22 03:10

R.Costa