jQuery check if Cookie exists, if not create it
Asked Answered
M

5

42

I cannot get this code to work I must be missing something pretty simple. I am trying to check to see if a Cookie exists, if it does {do nothing} if it doesn't {create it}. I am testing the cookie by including an alert on a page. Basically I do not want the cookie to keep re-creating with a referral url, I am trying to grab only the FIRST referred URL.

$(document).ready(function(){   
  if ($.cookie('bas_referral') == null ){
   var ref = document.referrer.toLowerCase();  
   // set cookie  
   var cookURL =  $.cookie('bas_referral', ref, { expires: 1 }); 
  } 
 });  

Displaying the current cookie contents:

    // get cookie  
    alert($.cookie('bas_referral'));  

    // delete cookie  
     $.cookie('bas_referral', null);
Maxillary answered 15/6, 2011 at 18:44 Comment(3)
Appears to be working just fine: jsfiddle.net/niklasvh/wxFvG. Have you included the $.cookie plugin source code in your page?Leatriceleave
Are you opening the page by HTTP? (and thus not from local disk file system) What cookie plugin are you using? What time unit is the expires value? Seconds? So, it expires in 1 second?Fritzfritze
I am using the jquery.cookie.js plugin and my alert displays the previous URL I was on, so I believe the cookie is being created. HOWEVER, if I were to go to different pages throughout the site, the alert displaying the cookie URL will change, it shouldn't being I set an IF-Statement.Maxillary
Q
88

I think the bulletproof way is:

if (typeof $.cookie('token') === 'undefined'){
 //no cookie
} else {
 //have cookie
}

Checking the type of a null, empty or undefined var always returns 'undefined'

Edit: You can get there even easier:

if (!!$.cookie('token')) {
 // have cookie
} else {
 // no cookie
}

!! will turn the falsy values to false. Bear in mind that this will turn 0 to false!

Quinte answered 28/4, 2014 at 15:11 Comment(9)
WARNING: typeof null === 'object' as Dan comments below.Fishery
this is the correct answer for the given question, @foo! While I tested the code, the true false context was vice versa: if (!!$.cookie('token')) { // have cookie } else { // no cookie }Choking
woah! it checks null, empty and undefined! Didn't know there's a shorter way to check those three before. NiceRimmer
what if the value of the cookie was false? probably better to check null and undefinedPortal
@foo the shorter answer isnt working for me. it is showing the opposite as to what the answer says - for me at least!Woolsey
The short answer with !! will trigger the eslint style check error: no-extra-boolean-cast. Better to use the typeof check, just in caseYokoyama
My non-existing cookies were "null" but not "undefined"Walk
hey @Walk see the Edit section: !!$.cookie('token') returns falseQuinte
<script type="text/javascript" src="cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/…> add this in your header to make sure it worksBruiser
D
26
 $(document).ready(function() {

     var CookieSet = $.cookie('cookietitle', 'yourvalue');

     if (CookieSet == null) {
          // Do Nothing
     }
     if (jQuery.cookie('cookietitle')) {
          // Reactions
     }
 });
Decant answered 16/12, 2011 at 16:24 Comment(3)
i don't know why but this is setting a cookie, not checking if one exists, very strange!Cylix
var CookieSet = $.cookie('cookietitle', 'yourvalue'); not works on my pc, what can be the reason? I'm using although jquery 1.9.1 library.Pascoe
Hmm I found the reason; I didn't have been installed the plugin from GitHub, I realised this was a native function. People who read this should download the plugin from (thank you @Kazar) : github.com/carhartl/jquery-cookiePascoe
K
10

I was having alot of trouble with this because I was using:

if($.cookie('token') === null || $.cookie('token') === "")
{
      //no cookie
}
else
{
     //have cookie
}

The above was ALWAYS returning false, no matter what I did in terms of setting the cookie or not. From my tests it seems that the object is therefore undefined before it's set so adding the following to my code fixed it.

if($.cookie('token') === null || $.cookie('token') === "" 
    || $.(cookie('token') === "null" || $.cookie('token') === undefined)
{
      //no cookie
}
else
{
     //have cookie
}
Kathlyn answered 10/12, 2013 at 22:13 Comment(0)
A
2

You can set the cookie after having checked if it exists with a value.

 $(document).ready(function(){            
      if ($.cookie('cookie')) { //if cookie isset
         //do stuff here like hide a popup when cookie isset
         //document.getElementById("hideElement").style.display = "none";
      }else{
         var CookieSet = $.cookie('cookie', 'value'); //set cookie
      }       
 });
Aeroembolism answered 9/6, 2016 at 14:36 Comment(0)
D
1

Try this very simple:

            var cookieExist = $.cookie("status");
            if(cookieExist == "null" ){
                alert("Cookie Is Null");

            }
Douglas answered 27/4, 2018 at 4:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.