Here I developed AJAX Polls, for TT. It is quite easy and I've done the code and testing so all is well.
How it works: User is presented with Poll. Radio fields with choices are displayed. They vote, and they get a success
message, it automatically switches to results (no refresh happening at all here).
The old one was bloated, old and made no sense for the routines accomplishing exactly the code below. So we replace.
First, create ajax_polls_get.php
Next, create ajax_polls_post.php
Delete or Backup the old poll tables. Now execute query
Now add to header.php
Now this is the full piece of go into a block or footer.php - I don't know your template - please request block or footer in comments and I will update the code.
Lastly, add to styles.css
[ATTACH type="full"]5629[/ATTACH]
[ATTACH type="full"]5630[/ATTACH]
AS votes increase so will the length of the bar. This is due to the JS function I added roundVote(). Enjoy! ? :alien:
How it works: User is presented with Poll. Radio fields with choices are displayed. They vote, and they get a success
message, it automatically switches to results (no refresh happening at all here).
The old one was bloated, old and made no sense for the routines accomplishing exactly the code below. So we replace.
First, create ajax_polls_get.php
<?
// AJAX Polls - GET (title, description, options & votes : id) - July 12, 2020
try {
$dsn = 'mysql:dbname=database;host=localhost';
$user = 'username';
$password = 'password';
$conn = new PDO($dsn, $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
die('Unable to connect to database');
}
$stmt = $conn->prepare("SELECT polls.id, polls.title, polls.desc, poll_answers.id AS answer, poll_answers.poll_id, poll_answers.title, poll_answers.votes AS votes FROM polls LEFT JOIN poll_answers ON polls.id = poll_answers.poll_id");
$stmt->execute();
$pollData = array();
if ($stmt->rowCount() > 0) {
$poll = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($poll as $row => $data) {
$data['id'] = $row['id'];
$data['poll_id'] = $row['poll_id'];
$data['title'] = $row['title'];
$data['votes'] = $row['votes'];
$data['answer'] = $row['answer'];
array_push($pollData, $poll);
}
}
echo json_encode($poll, JSON_UNESCAPED_SLASHES);
Next, create ajax_polls_post.php
<?
// AJAX Polls - POST (userid ? poll_answer : id) - July 12, 2020
try {
$dsn = 'mysql:dbname=database;host=localhost';
$user = 'username';
$password = 'password';
$conn = new PDO($dsn, $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
}
catch (PDOException $e) {
die('Unable to connect to database');
}
if (isset($_POST['userid'])) {
$stmt = $conn->prepare('SELECT * FROM polls');
$stmt->execute();
$poll = $stmt->fetch(PDO::FETCH_ASSOC);
if ($poll) {
$stmt = $conn->prepare('SELECT * FROM poll_answers WHERE poll_id = :id');
$stmt->bindParam(":id", $_POST['id'], PDO::PARAM_INT);
$stmt->execute();
$poll_answers = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (isset($_POST['poll_answer'])) {
$stmt = $conn->prepare('UPDATE poll_answers SET votes = votes + 1 WHERE id = :answer');
$stmt->bindParam(":answer", $_POST['poll_answer'], PDO::PARAM_INT);
$stmt->execute();
$user = "UPDATE users SET poll_voted = 'yes' WHERE id = :userid";
$stmt = $conn->prepare($user);
$stmt->bindParam(":userid", $_POST['userid'], PDO::PARAM_INT);
$stmt->execute();
echo "<div id=\"recent-poll\"></div>"; // Retrieve poll results
}
} else {
die('Poll ID does not exist.');
}
} else {
die('User ID does not exist.');
}
?>
Delete or Backup the old poll tables. Now execute query
CREATE TABLE `poll_answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`poll_id` int(11) NOT NULL,
`title` text NOT NULL,
`votes` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE `polls` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` text NOT NULL,
`desc` text NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
ALTER TABLE users ADD poll_voted ENUM('no','yes') NOT NULL;
Now add to header.php
<script>
// AJAX Polls - POST
$(function (e) {});
$("#form-poll").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "/ajax/ajax_polls_post.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
$("#poll-msg").fadeIn();
$("#vote-err").fadeOut();
},
success: function (data) {
if (data == 'invalid') {
// Invalid choice
$("#vote-err").html("Invalid vote").fadeIn();
} else {
// Poll success
$(".content").fadeOut();
$("#vote-success").html("Vote submitted.").delay(1000).fadeIn().delay(2000).fadeOut();
$("#poll-results-title").fadeIn();
// Retrieve poll results
$("#refresh-poll").html(data).fadeIn();
}
},
error: function (e) {
$("#vote-err").html(e).fadeIn();
}
});
}));
// Round votes (bar width)
function roundVotes(votes) {
return Math.round(votes * 1) * 10;
}
// AJAX Polls - GET
function fetchPollData() {
$(function(){});
$.ajax({
url: "/ajax/ajax_polls_get.php",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
html_to_append +=
'<div class="content poll-result"><div class="wrapper"><div class="poll-question"><p>' +
item.title +
' - <span style="font-weight:bold">' + item.votes + ' Votes</span></p><div class="result-bar" style="width:' + roundVotes(item.votes) + '%">' + item.votes + ' Votes</div></div></div></div>';
});
$("#recent-poll").html(html_to_append);
}
});
}
fetchPollData();
setInterval(function () {
fetchPollData()
}, 10000);
</script>
Now this is the full piece of go into a block or footer.php - I don't know your template - please request block or footer in comments and I will update the code.
<? if ($CURUSER && $CURUSER["poll_voted"] == "yes"){ ?>
<!-- Live Voting AJAX : Already Voted (View Votes) -->
<div id="recent-poll"></div>
<? } elseif ($CURUSER) { ?>
<!-- Live Voting : Options -->
<?
try {
$dsn = 'mysql:dbname=database;host=localhost';
$user = 'username';
$password = 'password';
$conn = new PDO($dsn, $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
die('Unable to connect to database');
}
$stmt = $conn->prepare('SELECT * FROM polls');
$stmt->execute();
$poll = $stmt->fetch(PDO::FETCH_ASSOC);
if ($poll) {
$stmt = $conn->prepare('SELECT * FROM poll_answers');
$stmt->execute();
$poll_answers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
die('Poll does not exist.');
}
?>
<h1>Poll: <?=$poll['title']?></h1>
<div class="content poll-vote">
<form action="/ajax/ajax_polls_post.php" method="post" id="form-poll">
<fieldset>
<? for ($i = 0; $i < count($poll_answers); $i++): ?>
<input type="radio" name="poll_answer" id="<?=$poll_answers[$i]['id']?>" value="<?=$poll_answers[$i]['id']?>"<?=$i == 0 ? ' checked' : ''?>>
<label for="<?=$poll_answers[$i]['id']?>">
<?=$poll_answers[$i]['title']?>
</label>
<? endfor; ?>
<div>
<input type="submit" value="Vote">
<a href="/result.php?id=<?=$poll['id']?>">View Result</a>
</div>
</fieldset>
<input type="hidden" name="userid" value="<? echo $CURUSER['id']; ?>">
</form>
</div>
<!-- Events -->
<div id="vote-success"></div>
<div id="vote-err"></div>
<div id="poll-msg"></div>
<div id="refresh-poll"></div>
<? } ?>
Lastly, add to styles.css
.poll-vote form {
display: flex;
flex-flow: column;
}
.poll-vote form label {
padding-bottom: 10px;
}
.poll-vote form input[type="radio"] {
transform: scale(1.1);
}
.poll-vote form input[type="submit"], .poll-vote form a {
display: inline-block;
padding: 8px;
border-radius: 5px;
background-color: #38b673;
border: 0;
font-weight: bold;
font-size: 14px;
color: #FFFFFF;
cursor: pointer;
width: 150px;
margin-top: 15px;
}
.poll-vote form input[type="submit"]:hover, .poll-vote form a:hover {
background-color: #32a367;
}
.poll-vote form a {
text-align: center;
text-decoration: none;
background-color: #37afb7;
margin-left: 5px;
}
.poll-vote form a:hover {
background-color: #319ca3;
}
.poll-result .wrapper {
display: flex;
flex-flow: column;
}
.poll-result .wrapper .poll-question {
width: 50%;
padding-bottom: 5px;
}
.poll-result .wrapper .poll-question p {
margin: 0;
padding: 5px 0;
}
.poll-result .wrapper .poll-question p span {
font-size: 14px;
}
.poll-result .wrapper .poll-question .result-bar {
display: flex;
height: 25px;
min-width: 30%;
max-width: 475px;
background-color: #266F30;
border-radius: 5px;
font-size: 14px;
color: #FFFFFF;
justify-content: center;
align-items: center;
}
[ATTACH type="full"]5629[/ATTACH]
[ATTACH type="full"]5630[/ATTACH]
AS votes increase so will the length of the bar. This is due to the JS function I added roundVote(). Enjoy! ? :alien:

