AJAX + PHP voting system

2019-08-03 17:53发布

问题:

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

 }