This tutorial will create a simple voting system using PHP and jQuery AJAX. In this system, a visitor can vote (either up or downvote) only once, which will be restricted by their IP address.
In this example, we have up, and downvote handlers triggered on an event basis. This handler calls a PHP page via AJAX and sends voting parameters to it. On that PHP page, we will execute queries to update the voting status in the database.
This code contains PHP code for getting value for the up and down vote button attributes. These values will be varied based on the current voting status.
The above list is dynamic from the database. This code has the HTML post list loaded from the database results retrieved.
The application DataSource fetches the results from a database table named “links.” Then it returns the associative array to form the HTML with Up and Down voting options.
index.html
<?php
require_once __DIR__ . "/DataSource.php";
$database = new DataSource();
$query = "SELECT * FROM links";
$result = $database->select($query);
?>
<HTML>
<HEAD>
<TITLE>PHP Voting System with jQuery AJAX</TITLE>
<meta name="viewport" content="width=device-width , initial-scale=1.0">
<link href="assets/css/style.css" rel="stylesheet" type="text/css">
<script src="https://code.jquery.com/jquery-3.6.1.min.js"
integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="
crossorigin="anonymous"></script>
<script type="text/javascript" src="assets/js/vote.js"></script>
</HEAD>
<BODY>
<table class="demo-table">
<tbody>
<?php
if (! empty($result)) {
$ip_address = $_SERVER['REMOTE_ADDR'];
foreach ($result as $links) {
?>
<tr>
<td valign="top">
<div class="feed_title"><?php echo $links["title"]; ?></div>
<div id="links-<?php echo $links["id"]; ?>">
<input type="hidden"
id="votes-<?php echo $links["id"]; ?>"
value="<?php echo $links["votes"]; ?>">
<?php
$vote_rank = 0;
$query = "SELECT SUM(vote_rank) as vote_rank FROM ipaddress_vote_map WHERE link_id = ? AND ip_address = ?";
$paramType = 'is';
$paramValue = array(
$links["id"],
$ip_address
);
$row = $database->select($query, $paramType, $paramValue);
$up = "";
$down = "";
if (! empty($row[0]["vote_rank"])) {
$vote_rank = $row[0]["vote_rank"];
if ($vote_rank == - 1) {
$up = "enabled";
$down = "disabled";
}
if ($vote_rank == 1) {
$up = "disabled";
$down = "enabled";
}
}
?>
<input type="hidden" id="vote_rank_status-<?php echo $links["id"]; ?>"
value="<?php echo $vote_rank; ?>">
<div class="btn-votes">
<input type="button" title="Up" class="up"
onClick="addVote(<?php echo $links["id"]; ?>,'1')"
<?php echo $up; ?> />
<div class="label-votes"><?php echo $links["votes"]; ?></div>
<input type="button" title="Down"
class="down"
onClick="addVote(<?php echo $links["id"]; ?>,'-1')"
<?php echo $down; ?> />
</div>
</div>
<div class="desc"><?php echo $links["description"]; ?></div>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</BODY>
</HTML>
This jQuery function calls PHP to update the voting status based on the vote request of the visitors. And then, it calculates the current total votes and the vote status of the particular visitor by IP. The script is,
It classifies the up and down voting actions and handles them with a JavaScript switch statement. Once sending the voting flag to the database, the JavaScript AJAX script highlights up or down voting controls recently clicked. Also, it updates the voting count on the corresponding row.
assets/js/vote.js
function addVote(id, vote_rank) {
$.ajax({
url: "add-vote-ajax.php",
data: 'id=' + id + '&vote_rank=' + vote_rank,
type: "POST",
beforeSend: function() {
$('#links-' + id + ' .btn-votes').html("<img src='LoaderIcon.gif' />");
},
success: function(vote_rank_status) {
var votes = parseInt($('#votes-' + id).val());
var vote_rank_status;
switch (vote_rank) {
case "1":
votes = votes + 1;
break;
case "-1":
votes = votes - 1;
break;
}
$('#votes-' + id).val(votes);
$('#vote_rank_status-' + id).val(vote_rank_status);
var up, down;
if (vote_rank_status == 1) {
up = "disabled";
down = "enabled";
}
if (vote_rank_status == -1) {
up = "enabled";
down = "disabled";
}
var vote_button_html = '<input type="button" title="Up" class="up" onClick="addVote(' + id + ',\'1\')" ' + up + ' /><div class="label-votes">' + votes + '</div><input type="button" title="Down" class="down" onClick="addVote(' + id + ',\'-1\')" ' + down + ' />';
$('#links-' + id + ' .btn-votes').html(vote_button_html);
}
});
}
This code receives AJAX data-string and passes these values to database queries to update the voting status.
add-vote-ajax.php
<?php
if (! empty($_POST["id"])) {
require_once __DIR__ ."/DataSource.php";
$database = new DataSource();
$query = "INSERT INTO ipaddress_vote_map (ip_address,link_id,vote_rank) VALUES (?, ?, ?)";
$paramType = 'sii';
$paramValue = array(
$_SERVER['REMOTE_ADDR'],
$_POST["id"],
$_POST["vote_rank"]
);
$result = $database->insert($query, $paramType, $paramValue);
if (! empty($result)) {
switch ($_POST["vote_rank"]) {
case "1":
$update_query = "UPDATE links SET votes = votes+1 WHERE id= ?";
$paramType = 'i';
$paramValue = array(
$_POST["id"]
);
break;
case "-1":
$update_query = "UPDATE links SET votes = votes-1 WHERE id= ?";
$paramType = 'i';
$paramValue = array(
$_POST["id"]
);
break;
}
$result = $database->update($update_query, $paramType, $paramValue);
$query = "SELECT SUM(vote_rank) as vote_rank FROM ipaddress_vote_map WHERE link_id = ? and ip_address = ?";
$paramType = 'is';
$paramValue = array(
$_POST["id"],
$_SERVER['REMOTE_ADDR']
);
$row = $database->select($query, $paramType, $paramValue);
print $row[0]["vote_rank"];
}
}
?>