Javascript – Check if cookie is set

Hi everyone i want to redirect a user to another page if the cookie is set by clicking the button.

Read More
<a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"><button type="button" name="accept" class="btn btn-success">Button Text</button> 
<script>
    function SetCookie(c_name,value,expiredays)
        {
            var exdate=new Date()
            exdate.setDate(exdate.getDate()+365)
            document.cookie=c_name+ "=" +escape(value)+
            ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +
            ("; path=/")
    		location.reload()
        }
        
    if 
        
</script>

Works and i also got the if statement in php but i want it in javascript because of wordpress issues. In php it would look like this.

    <?php
$cookie_name = "anyname";
$cookie_value = "anycontent";
If (isset($_COOKIE[$cookie_name])) {
// action if cookie is set  
}
?>

i can’t seem to figure it out in javascript, and i also looked around on the web

After doing this:

<a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"><button type="button" name="accept" class="btn btn-success">Button Text</button> 
<script>
    function SetCookie(c_name,value,expiredays) {
            var exdate=new Date()
            exdate.setDate(exdate.getDate()+365)
            document.cookie=c_name+ "=" +escape(value)+
            ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +
            ("; path=/")
    		location.reload()
        }
       
    mycookieValue = getCookie("pecCookie")
    if(mycookieValue) {
        window.location = "193.91.113.21/downloads/";
    }
    
function getCookie(c_name) {
    var re = new RegExp(c_name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return (value != null) ? unescape(value[1]) : null;
}
        
</script>

it keeps going to the redirect even without the cookie

Related posts

2 comments

  1. Here is a function for get the cookie value in javascript.

    mycookieValue = getCookie("mycookieName")
    
    if(mycookieValue)
    {
      //Your code here
    }
    
    function getCookie(name)
    {
        var re = new RegExp(name + "=([^;]+)");
        var value = re.exec(document.cookie);
        return (value != null) ? unescape(value[1]) : null;
    }
    
  2. I will suggest you use jQuery cookie.js library. You can download it from here.. https://github.com/carhartl/jquery-cookie

    Example:

     //Set Cookie
     $.cookie('userName', 'John');
    
    //Read Cookie Value
    var username= $.cookie('userName');
    console.log(username);
    
    //Remove a cookie
    $.removeCookie('username'); 
    //Cookie is removed then above line will return true
    
    //Check cookie in if else
    
    if(username){
      console.log(username);
    }
    
    // or you can do this also
    if(username=='John'){
      console.log('User Name is '+username);
    }
    

    Hope this will help you.

Comments are closed.