Eric ERK
Eric ERK

Reputation: 369

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.

Upvotes: 0

Views: 621

Answers (2)

alextunyk
alextunyk

Reputation: 799

Here is a good example of setting cookies with javascript w3schools demo And I doubt it will be possible to set cookies to other domains except the origin of the page.

With PHP it is done in the next way: 1st you send http request to the server using javascript native xhr or jquery etc. and then php script must set cookie headers and return back to client. In this case browser will automatically set cookies received in headers.

Upvotes: 0

Zsw
Zsw

Reputation: 4107

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";
});

Upvotes: 2

Related Questions