Skip to content
Advertisement

Setting Cookie on click

I’m having an issue creating / setting a cookie on the click of a link, is there a proper way to do this? Either PHP or Javascript is fine.

<html>
    <a href="2.html" id="cookie"> 
        <div class="yes">    
            <p>Yes</p>   
        </div>
    </a> 
</html>

<script>
    $("a#cookie").bind("click", function() {

    });
</script>

<?php
    setcookie( "cookie")
?>

Obviously both JS and PHP wouldn’t exist in the same instance it was just to show what I have.

Advertisement

Answer

You can’t mix JavaScript and PHP. By the time your JavaScript code loads, your PHP code would have already executed.

In your case, it may be easier for you to set cookies without using PHP.

$("a#cookie").bind("click", function() {
    document.cookie="cookie=value";
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement