I'm doing a fairly primitive voting system with PHP.
MySQL PHP
while($row = mysql_fetch_array($query)): ?>
<div class="item" data-postid="<?php echo $row['id'] ?>" data-score="<?php echo $row['vote'] ?>">
<div class="vote-span"><!-- voting-->
//
<div class="vote" data-id="<?php echo $row['id']?>" data-action="up" title="Vote up">
//
<img src="//placekitten.com/10/10"/>
</div><!--vote up-->
<div class="vote-score"><?php echo $row['vote'] ?></div>
//
<div class="vote" data-id="<?php echo $row['id']?>" data-action="down" title="Vote down">
//
<img src="//placekitten.com/g/10/10"/>
</div><!--vote down-->
</div>
<div class="post"><!-- post data -->
<h2><?php echo $row['name']?></h2>
<p><?php echo $row['title'] ?></p>
</div>
</div><!--item-->
<?php endwhile?>
I'm mostly focused at the text between the //
. First, I set two data attributes in hopes of using them later with javascript; I set data-action
to either up
or down
to tell if it was an upvote or a downvote. I also set the data-id
attribute to the current row ID key from my MySQL table.
Through my logic, I could then go through javascript jquery and cause the PHP code to execute when clicked, and add/subtract the number from the correct row in MySQL.
I tried the Javascript just more or less as an expirement:
$('.vote').click(function(){
if ($(this).data('action')=='up'){
//PHP code here
}
});
Needless to say, that didn't work, since PHP and Javascript don't play like that since PHP is serverside. Next, I thought I could call a PHP function in my Javascript conditional - but there seems like there must be an easier way to do what I am attempting. I've been looking at numerous tutorials, and they're either outdated or specific to other projects. I checked around SO, and found this question, but it's geared towards allowing an IP to have vote limitations. This question looks similar to what I'm doing, except I can't really figure out how they have it set up, as they don't have how they call the function
TL;DR My problem is calling a PHP function on a div click that will place data into the correct ID of a MySQL row. AJAX seems the way to go, but I'm unsure on how to implement it.