0

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.

Mafia
  • 792
  • 2
  • 19
  • 39
  • 2
    Please try to ask one question with one code sample and one answer. – Ry- May 26 '12 at 01:13
  • I bet your ajax call is getting cached in the browser. – asawyer May 26 '12 at 01:13
  • 1
    @asawyer: POST requests are never cached. – Ry- May 26 '12 at 01:14
  • @minitech : My post's question is: `Problem: When I click "Vote up" or "Vote down", it doesn't return anything. Nothing happens on the page, at all.` And I attached the **3 codes** provided, which are possible sources of the problem. I can't figure out which one of them is the problem though. – Mafia May 26 '12 at 01:17
  • @Love do you see any errors in your browsers console? – bPratik May 26 '12 at 01:19
  • @bPratik : Exactly how do I check this bPratik? On my browser itself, there are no problems, or errors, when I click on the voting buttons. The page just looks like it ignored or doesn't know about the click/vote. – Mafia May 26 '12 at 01:21
  • @Love which browser are you using? Chrome, for instance, shows all exceptions (including syntax errors) on the console. Firefox omits some (for instance, doesn't show if there is a syntax error, even with Firebug - just doesn't load the script, so you can't find it in the "scripts" list). Dunno about other browsers. – mgibsonbr May 26 '12 at 01:23
  • @mgibsonbr : I both have Chrome and Firefox open right now, & doing checking on both. I don't know how to check for browser errors though, but there's nothing happening that is out of the ordinary for my browsers, it doesn't seem like I'm having any errors. – Mafia May 26 '12 at 01:26
  • @minitech Hmm got me there don't you. – asawyer May 26 '12 at 01:27
  • Are you testing on your local machine, by any chance? I smell an origin control issue here. – vzwick May 26 '12 at 01:27
  • 3
    @Love on Chrome, press **F12** to bring up developer tools. In there you'll find the `Console` – bPratik May 26 '12 at 01:28
  • @vzwick how exactly? I've tested local `PHP` + `AJAX` setup without issues? Maybe I'm missing something! – bPratik May 26 '12 at 01:30
  • @Love can you host this setup online? Maybe a dummy server where we can test, as it is too late in the night for me to be bothered setting up a workbench! – bPratik May 26 '12 at 01:31
  • @vzwick : I am checking using my computer, if that is what a local machine is. :) @bPratik : Thanks, I saw this error **Uncaught TypeError: Cannot call method 'click' of null** here: `$(function(){ $("a.vote_up").click(function(){ Uncaught TypeError: Cannot call method 'click' of null //get the id the_id = $(this).attr('id');` – Mafia May 26 '12 at 01:32
  • @bPratik - `localhost` is considered a non-origin by most browsers out there. At least for remote calls - not sure about those to localhost itself right now. – vzwick May 26 '12 at 01:32
  • 1
    @Love do you by any chance have other frameworks in the same page besides jQuery? (ex. prototype.js) `$(something)` should **never** be `null`. I see the main function is being called, or the code wouldn't reach that point to raise that error. Try explicitly using `jQuery.click` instead of `$.click` and see what happens. – mgibsonbr May 26 '12 at 01:37
  • I saw this error **Uncaught TypeError: Cannot call method 'click' of null** here: `$(function(){ $("a.vote_up").click(function(){ Uncaught TypeError: Cannot call method 'click' of null //get the id the_id = $(this).attr('id');` When I click on the error to collapse: `Uncaught TypeError: Cannot call method 'click' of null index.php:6 (anonymous function) index.php:6 o.extend.ready.o.readyList jquery.pack.js:19 o.extend.each jquery.pack.js:12 o.extend.ready jquery.pack.js:19 o.each.o.fn.(anonymous function)` – Mafia May 26 '12 at 01:41
  • @mgibsonbr : Yes, as a matter of fact on my header I, as well, have: `` I replaced **$.click** with **jQuery.click**, and the error that shows up is: `Uncaught TypeError: Object javascript:; has no method 'attr' ` – Mafia May 26 '12 at 01:46

2 Answers2

2

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.

mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
0

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>
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Vicky
  • 9,515
  • 16
  • 71
  • 88