AJAX + PHP voting system

一世执手 提交于 2019-12-11 06:15:32

问题


I'm working on a voting system in AJAX and PHP and I've run into a bit of trouble. We're displaying a bunch of posts from our database and each post has an image next to it -- clicking the image is supposed to 1) toggle the image colour and then 2) use AJAX call a PHP script which then decides whether to add or subtract a vote. I have the image toggle working, but I'm not sure how to do the next part. What's the best way to do this?

This is the while-loop which outputs the posts:

while($row = mysql_fetch_array($result))

          {

    ?>

        <li class = "post">
            <a href = "#" onclick = "return toggle(this,'heart<?php echo $row['post_id'];?>')"><img name = "heart<?php echo $row['post_id'];?>" src = "/images/heart.png" class = "thumbnail" width = "15"  /></a>
            <p class = "title"><img class = "favicon" width = "16" height = "16" src = "<? echo $row['favicon']; ?>" /><a href = "<? echo $row['post_url']; ?>" target = "_blank"><? echo $row['post_title']; ?></a></p>
            <p class = "postinfo">posted <? echo doRelativeDate( $row['date'] ); ?> by <a href = "<? echo $row['blog_url'];?>"><? echo $row['blog_name']; ?></a>
        </li>

    <?
        }
    ?>

回答1:


" src = "/images/heart.png" class = "thumbnail" width = "15" id="voteImage />

add one ID to your image. catch click event on this Id by any javascript framework.

I am giving example in jQuery.

 jQuery("#voteImage").live("click",function(){
        var imageName = jQuery(this).attr('name');
        var postId = imageName.substr(5);  //Here you will have post Id because remove heart from heart20

        //now you can hit ajax call to your vote-up or vote-Down php with postId
        jQuery.ajax({
             type: 'POST',
            url: baseURI+'voteup.php',
            data:"postId="+postId,
            cache: false,
            success: function(result)
                    {
                    //perform further action like give alert to user that action performed
                    }
        });

 }


来源:https://stackoverflow.com/questions/3604953/ajax-php-voting-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!