Search code examples
javascriptphpcookiessession-cookiessetcookie

Onclick Sets a Cookie For a Page


I Have this button on my site which opens new page on click, so i was trying to set a unique cookie for every users who click on it and access the new page , if someone try to access the new page directly by url than they should see a sample text and redirect automatically to the button page. How can i do that?

<div class="button">
 <a href="/" target="_blank">CLICK HERE TO GET THIS..!</a>
</div>

Solution

  • HTML:

    <div class="button">
         <a href="" onclick="what_i_want()" id="the_button" target="_blank">CLICK HERE TO 
         GET THIS..!</a>
    </div>
    

    JS :

    <script>
    function what_i_want()
    {
        var cookie_name=Math.floor(Math.random() * 1000000) + 1;  //random name for example;
        var cookie_value=" any value";  // << you also can get value from function >> what_i_want(par,par2,par,3);
        document.cookie = cookie_name +'='+ cookie_value;
        document.getElementById('the_button').href="TARGET_LOCATION";
    }
    </script>