Вопрос

Trying to make this Reddit-style Voting With PHP, MySQL And jQuery work.

Problem: When I click "Vote up" or "Vote down", it doesn't return anything. Nothing happens on the page, at all.
I have established that the votes.php page is working though, but can't figure out why the rest is not.

Basically, there are 3 sets of codes:
01. jQuery scripts that goes into the <head>,
02. html inside the <body> (displays: voting buttons and results) / index.php...
03. the PHP page (votes.php) where jquery sends the action to.


01.) Placed within my <head>:

<script type="text/javascript" src="http://site.com/js/jquery.pack.js"></script>

<script type="text/javascript">
$(function(){
    $("a.vote_up").click(function(){
    //get the id
    the_id = $(this).attr('id');

    // show the spinner
    $(this).parent().html("<img src='images/spinner.gif'/>");

    //fadeout the vote-count 
    $("span#votes_count"+the_id).fadeOut("fast");

    //the main ajax request
        $.ajax({
            type: "POST",
            data: "action=vote_up&id="+$(this).attr("id"),
            url: "votes.php",
            success: function(msg)
            {
                $("span#votes_count"+the_id).html(msg);
                //fadein the vote count
                $("span#votes_count"+the_id).fadeIn();
                //remove the spinner
                $("span#vote_buttons"+the_id).remove();
            }
        });
    });


    $("a.vote_down").click(function(){
    //get the id
    the_id = $(this).attr('id');

    // show the spinner
    $(this).parent().html("<img src='images/spinner.gif'/>");

    //the main ajax request
        $.ajax({
            type: "POST",
            data: "action=vote_down&id="+$(this).attr("id"),
            url: "votes.php",
            success: function(msg)
            {
$("span#votes_count"+the_id).fadeOut().html(msg).fadeIn();
                $("span#vote_buttons"+the_id).remove();
            }
        });
    });
}); 
</script>

02.) Placed within the loop inside <body>:
(Voting buttons & where results should show)

<div class=\"entry\">
 <span class=\"votes_count\" id=\"votes_count" .$id. "\">" .$effective_vote. " votes</span>  

 <span class=\"vote_buttons\" id=\"vote_buttons" .$id. "\">  
  <a href=\"javascript:;\" class=\"vote_up\" id=\"" .$id. "\">Vote Up!</a>  
  <a href=\"javascript:;\" class=\"vote_down\" id=\"" .$id. "\">Vote Down!</a>  
 </span>  

</div>

03.) My votes.php page (where the action happens):

// Database connection here //

function getAllVotes($id)
    {
    $votes = array();
    $q = "SELECT * FROM cover WHERE id='$id' ";
    $r = mysql_query($q) or die("Error: ". mysql_error(). " with query ". $q);
    if(mysql_num_rows($r)==1) {

        $row = mysql_fetch_assoc($r);
        $votes[0] = $row['votes_up'];
        $votes[1] = $row['votes_down'];
        }
    return $votes;
    }

function getEffectiveVotes($id)
    {
    /**
    Returns an integer
    **/
    $votes = getAllVotes($id);
    $effectiveVote = $votes[0] - $votes[1];
    return $effectiveVote;
    }

$id = $_POST['id'];
$action = $_POST['action'];

//get the current votes
$cur_votes = getAllVotes($id);

//ok, now update the votes

if($action=='vote_up') //voting up
{
    $votes_up = $cur_votes[0]+1;
    $q = "UPDATE cover SET votes_up = $votes_up WHERE id = $id";
}
elseif($action=='vote_down') //voting down
{
    $votes_down = $cur_votes[1]+1;
    $q = "UPDATE cover SET votes_down = $votes_down WHERE id = $id";
}

$r = mysql_query($q);
if($r) //voting done
    {
    $effectiveVote = getEffectiveVotes($id);
    echo $effectiveVote." votes";
    }
elseif(!$r) //voting failed
    {
    echo "Failed!";
    }

Specifically, what I especially like about this compared to other rating methods provided online, is that it returns the sum total number of votes (subtracts # of vote-downs from vote-ups, and returns that value).

I do not do a lot of jQuery or ajax, it confuses me at times, but I have very basic simple knowledge. (I usually just follow the codes)

+ Also, how do I make this into a PDO version, rather than using MySQL Queries? I would appreciate it if someone could additionally help with this. :o)

Not sure how to notify a user on StackOverflow, but the developer of this project was:
User: abhisek (user: 4507330)

Thanks for your time! Hopefully, someone can diagnose the source of the problem.

Это было полезно?

Решение

Since you're using jQuery and prototype.js in the same page, you need to be careful about how you use the $ function (since both frameworks claim that name). One option is replacing your main function with:

jQuery(function($) {
    ...
});

This way you'll be able to use $ as an alias for jQuery inside that block (but you won't be able to access prototype.js though). Another option is to use jQuery's noConflict. Check the docs for more information about how to use it.

Другие советы

You may like this Jquery Ajax Voting system

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-latest.js"></script>  
<script>
$(document).ready(function () {

    $(".voteMe").click(function() {
        var voteId = this.id;
        var upOrDown = voteId.split('_'); 
        $.ajax({
            type: "post",
            url: "<?= base_url();?>/index.php/article/voteMe",
            cache: false,               
            data:'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
            success: function(response){
                try{
                    if(response=='true'){   
                        var newValue = parseInt($("#"+voteId+'_result').text()) + 1;            
                        $("#"+voteId+'_result').html(newValue);
                    }else{
                        alert('Sorry Unable to update..');
                    }
                }catch(e) {     
                    alert('Exception while request..');
                }       
            },
            error: function(){                      
                alert('Error while request..');
            }
         });
    });

});
</script>
<style>
ul,ol,li{
    list-style-type: none;
}

h2{
    color: #2864B4;
    text-decoration: none;
}
</style>
</head>
<body>
<div class="container">
<?php
    if(is_array($VOTES) && count($VOTES) ) {
?>
<div>
    <ul>
    <?php foreach($VOTES as $loop){ ?>               
        <li>
        <div>
            <h2><?=$loop->VOTE_DESC;?></h2>
            <span><a id="<?=$loop->VOTE_ID;?>_upvote" class="voteMe"><img src="<?= base_url();?>/img/images/up_vote.png"/></a><span id="<?=$loop->VOTE_ID;?>_upvote_result" ><?=$loop->UP_VOTE;?></span></span>&nbsp;|&nbsp;
            <a id="<?=$loop->VOTE_ID;?>_downvote" class="voteMe"><img src="<?= base_url();?>/img/images/down_vote.png"/></a><span id="<?=$loop->VOTE_ID;?>_downvote_result" ><?=$loop->DOWN_VOTE;?></span>
        </div>
        </li>
    <?php }?>   
    </ul>
</div>
<?php }?>

</div>
</body>
</html>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top