使用rateyo插件设置数据库的评级值

时间:2016-05-01 12:37:57

标签: php jquery ajax rating

我在我的应用程序中使用这个rateyo插件。有一个页面,用户可以给实体评级。但在给出评级之前,我正在检查,如果该用户已经为该特定实体分配了评级,并且如果用户这样做,那么我从数据库获取评级值并将其设置为插件所说的。但如果是新用户,他可以提交新的评级。

这是我正在实施的代码:

$(document).ready(function(){
$("#rateYo").rateYo().on('rateyo.set',function(e, data){
            $.ajax({
                type : "post",
                url : "PostRatingValue.php",
                data : {
                    "rating" : data.rating,
                    "peopleid" : celeb_id,
                    "userid" : user_id
                },
                dataType : "json",
                success : function(response){
                    if(response.toString() == "true"){

                        $.growl.notice({ title: "Growl", message: "Rating<b> "+ data.rating +" </b>assigned successfully" });
                    }
                    else{
                        $.growl.error({ message: "<b>Unable to assign rating.</b>" });
                    }
                },
                error : function(response){
                    $.growl.error({ message: "<b>Something went terribly wrong! :'(.</b>" });
                }
            });
        });

下面是设置评级值的代码(如果存在)。

<?php
            if(isset($fetchRatingIdAndValue['ratingpoints'])){
        ?>  
                $("#rateYo").rateYo("option", "rating", <?php echo $fetchRatingIdAndValue['ratingpoints'];?>);
        <?php       
            }
        ?>
});

问题是,当设置旧评级时,会进行ajax调用,在表中再次插入相同的数据。我希望我的ajax调用仅在我需要设置新的评级或编辑之前的评级时才能工作。我无法找到出路。请帮忙。

1 个答案:

答案 0 :(得分:1)

在rateyo初始化后设置评级时,将在元素上触发rateyo.set事件。

请不要这样做,而是如果已经存在旧的评级,请在初始化期间传递它,如

$(document).ready(function(){
    $("#rateYo").rateYo({

      rating: <?php echo $fetchRatingIdAndValue['ratingpoints'];?>
    }).on('rateyo.set',function(e, data){

        $.ajax({
            type : "post",
            url : "PostRatingValue.php",
            data : {
                "rating" : data.rating,
                "peopleid" : celeb_id,
                "userid" : user_id
            },
            dataType : "json",
            success : function(response){
                if(response.toString() == "true"){

                    $.growl.notice({ title: "Growl", message: "Rating<b> "+ data.rating +" </b>assigned successfully" });
                }
                else{
                    $.growl.error({ message: "<b>Unable to assign rating.</b>" });
                }
            },
            error : function(response){
                $.growl.error({ message: "<b>Something went terribly wrong! :'(.</b>" });
            }
        });
    });
});
如果用户之前未给出任何评分,则

$fetchRatingIdAndValue['ratingpoints']应包含0