Jerome
Jerome

Reputation: 167

Upvote button on website with JavaScript, Php, AJAX, MySql not working. What am I doing wrong?

I'm trying to create upvote/downvote buttons on a list of articles that I get from a MySql database. The buttons work in the sense that you press on the button and it gets the id of the article. However I can't get the id from article page to the php voting page. When I press the button the database doesn't register the vote. What am I doing wrong?

    <script type="text/javascript">
    $(function() {

    $(".vote").click(function() 
    {


    var id = $(this).attr("id");
    var name = $(this).attr("name");
    var dataString = 'id='+ id ;
    var parent = $(this);


    if(name=='up')
    {
      alert('you upvoted on '+ dataString);

    $(this).fadeIn(200);
    $.ajax({
       type: "POST",
       url: "weblectureupvote.php",
       data: dataString,
       cache: false,

       });

    }
    else
    {
    alert('you downvoted on '+ dataString);
    $(this).fadeIn(200);
    $.ajax({
       type: "POST",
       url: "weblectureupvote.php",
       data: dataString,
       cache: false,

     });
   }
    return false;
      });

    });
    </script>

This is the php file:

<?php

$pid = $_POST['id'];

try {



$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$result=mysql_query("SELECT * FROM database WHERE pid = '$pid' ") or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
        // temp user array
        $lecturelist = array();
        $lecturelist["pid"] = $row["pid"];
        $lecturelist["upvote"] = $row["upvote"];
        $lecturelist["downvote"] = $row["downvote"];
        $lecturelist["vote"] = $row["vote"];

      }



$upvote= $row["upvote"];
$downvote = $row["downvote"];
$vote = $row["vote"];
$upvote = $upvote + 1;


$query = $db->prepare('UPDATE database SET upvote = :upvote WHERE pid = :pid');
$query->execute(array(  
  ':upvote'  => $upvote,
  ':pid'    => $pid
)); 
$query = $db->prepare('UPDATE database SET vote=:vote  WHERE pid = :pid');
$query->execute(array(  
  ':vote'  => $vote,
  ':pid'    => $pid
)); 


} catch(PDOException $e) {
  echo $e->getMessage();
}
?>

Upvotes: 0

Views: 818

Answers (1)

Ţ&#238;gan Ion
Ţ&#238;gan Ion

Reputation: 174

data: {id: id}

this will get to your php file a "id" variable ( this is the first id ) and with some value ( from the second id )

now

$pid = $_POST['id'];

this should work, as you weren't sending "much" to the server

Upvotes: 1

Related Questions