Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check if Cookie exists, if not create it

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); 
like image 385
ToddN Avatar asked Jun 15 '11 18:06

ToddN


People also ask

How check cookie is set or not in jQuery?

If this is the case, then you can actually check if a user has enabled cookies or not using the following straightforward jQuery snippet: $(document). ready(function() { var dt = new Date(); dt. setSeconds(dt.

How do you check if a cookie exists or not?

document. cookie. indexOf('cookie_name='); It will return -1 if that cookie does not exist.


1 Answers

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!

like image 91
Laszlo Avatar answered Sep 22 '22 20:09

Laszlo