Javascript - Check if cookie is set

admin

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

<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override">
Code:
&lt;a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"&gt;&lt;button type="button" name="accept" class="btn btn-success"&gt;Button Text&lt;/button&gt; 
&lt;script&gt;
    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 
        
&lt;/script&gt;
</div>
</div>


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.

Code:
    &lt;?php
$cookie_name = "anyname";
$cookie_value = "anycontent";
If (isset($_COOKIE[$cookie_name])) {
// action if cookie is set  
}
?&gt;

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

After doing this:

<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override">
Code:
&lt;a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"&gt;&lt;button type="button" name="accept" class="btn btn-success"&gt;Button Text&lt;/button&gt; 
&lt;script&gt;
    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;
}
        
&lt;/script&gt;
</div>
</div>


it keeps going to the redirect even without the cookie