1

I have like and dislike buttons for multiple posts on my view.

But I want to restrict the voting and hence use cookies which lasts for 7 days.

And I use the $("a.btn-success").click(function() function to calculate the success rate of the respective post and to set a cookie. But the php script that I use is setting the cookie even without the button being clicked.

<?php
   $expire=time()+60*60*24*30;
   setcookie("coupcookie", calledbyid, $expire);
?>

So if I just refresh the page, I can see that the cookie is set.

Could anyone please tell me what am I doing wrong here?

Thanks in advance.

edit

Here is my click function.

$("a.btn-success").click(function(){
        var calledby = $(this);
        var calledbyid=calledby.attr("id");
        <?php
             $expire=time()+60*60*24*30;
             setcookie("coupcookie", calledbyid, $expire);
        ?>
        var url = $(location).attr('href');
        var sub = window.location.pathname.split('/');
        alert("Hey button clicked "+calledbyid);
        $.post(url.replace(sub[2]+'/'+sub[3],'')+"home/vote",{ "id" : calledbyid, "vote" : 1 },  function(data){
            //alert("Hey post request completed");
            $.get(url.replace(sub[2]+'/'+sub[3],'')+"home/getsuccess", {"id": calledbyid}, function(result){
                $("#successrate"+calledbyid).html(result.concat('%'));
            }, "text").error(function(xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(thrownError);});

        }, "text").error(function(xhr, ajaxOptions, thrownError){
            alert(xhr.status);
            alert(thrownError);});
    });
4

3 回答 3

1

当您生成 Javascript 代码时,您正在设置 cookie

于 2012-09-26T06:56:15.650 回答
0

PHP 是一种服务器端技术,所以当您看到页面时 PHP已经完成了他的工作。因此,没有办法响应 php 中的客户端按钮点击(除了重新加载页面,但在您的情况下并非如此)。因此,您需要setcookie从 php 中删除并使用 jQuery 设置您的 cookie。

请参阅如何使用 jQuery 设置/取消设置 cookie?详情。

于 2012-09-26T06:56:06.607 回答
0

我建议您不要使用 PHP 来设置 cookie,而是使用jQuery它自己。因此,它将首先使用 this

该功能$("a.btn-success").click还将包括:

$.cookie("coupcookie", calledbyid, { expires : 7 });
于 2012-09-26T07:01:38.563 回答