Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
AJAX Polls v1
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / Torrent Trader / v3 Mods Completed

2020-07-15 04:48:52
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


<?
// 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:
Newpolls2.png
Newpolls2.png
NewPolls1.png
NewPolls1.png
2022-02-18 03:17:03
I like this. Is there any way you can just do your PDO magic and use the DB connection that TTv3 already has? Rather than entering it across multiple files? I dont know PDO stuff, so maybe its not doable mixing PDO and SQLI, Im just a hobbyist. Maybe write 1 function in the backend to cover all files? I will post the connector for your reference if it helps any
TTv3 database connection code (all data is gathered from the mysql.php file in backend)
function dbconn($autoclean = false) {
global $mysql_host, $mysql_user, $mysql_pass, $mysql_db, $THEME, $LANGUAGE, $LANG, $site_config;
$THEME = $LANGUAGE = null;

if (!ob_get_level()) {
if (extension_loaded('zlib') && !ini_get('zlib.output_compression'))
ob_start('ob_gzhandler');
else
ob_start();
}

header("Content-Type: text/html;charset=$site_config[CHARSET]");

function_exists("mysqli_connect") or die("MySQL support not available.");

   $GLOBALS["DBconnector"] = new mysqli($mysql_host, $mysql_user, $mysql_pass, $mysql_db);    // Check connection
   if ($GLOBALS["DBconnector"]->connect_error) {
      die("Connection failed: " . $GLOBALS["DBconnector"]->connect_error);
}


unset($mysql_pass); //security

userlogin(); //Get user info

//Get language and theme
$CURUSER = $GLOBALS["CURUSER"];

   $ss_a = mysqli_fetch_assoc(SQL_Query_exec("select uri from stylesheets where id='" . ( $CURUSER ? $CURUSER['stylesheet'] : $site_config['default_theme'] )  . "'"));
$THEME = $ss_a["uri"];

$lng_a = mysqli_fetch_assoc(SQL_Query_exec("select uri from languages where id='" .  ( $CURUSER ? $CURUSER['language'] : $site_config['default_language'] )  . "'"));
$LANGUAGE = $lng_a["uri"];

require_once("languages/$LANGUAGE");

if ($autoclean)
autoclean();
}

because this
        $dsn      = 'mysql:dbname=databse;host=localhost';
       $user     = 'name';
       $password = 'password';
       $conn     = new PDO($dsn, $user, $password);
       $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
       $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

is similar to this
    $GLOBALS["DBconnector"] = new mysqli($mysql_host, $mysql_user, $mysql_pass, $mysql_db);
   if ($GLOBALS["DBconnector"]->connect_error) {
      die("Connection failed: " . $GLOBALS["DBconnector"]->connect_error);

but I dont know what to do since your stuff is PDO, or maybe im overthinking it
TTv3 Micro Edition
Ubuntu 20.04.6 LTS Server
Mysql Version: 10.3.39-MariaDB-0ubuntu0.20.04.2
PHP Version: 7.4.3-4ubuntu2.20
Apache Version: Apache/2.4.59 (Ubuntu)
Last edited by MicroMonkey on 2022-02-18 03:28:50
2022-02-18 05:52:00
You would just need to change this query work

$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.');
}


I'd search "FROM polls" in editor get example and just play with it prepare would be the v3 exec function, fetch would be sqli_fetch_assoc etc just make new test.php file you would need to include functions.php and dbconn function at top but once you have the query everything else should work - not used this myself
2022-02-18 12:24:13
I got this. Seems correct. Have to test the rest of the files.
<?php
begin_block(T_("POLL"));
require_once ("backend/functions.php");

if ($CURUSER && $CURUSER["poll_voted"] == "yes") { ?>

   <!-- Live Voting AJAX : Already Voted (View Votes) -->
   <div id="recent-poll"></div>

<?php
} elseif ($CURUSER) { ?>

   <!-- Live Voting : Options -->
   <?php
   // try {
   //     $dsn      = 'mysql:dbname=database;host=localhost';
   //     $user     = 'user';
   //     $password = 'pass';
   //     $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 = SQL_Query_exec('SELECT * FROM polls');
//    $stmt->execute();
   $poll = mysqli_fetch_assoc($stmt);
   if ($poll) {
       $stmt = SQL_Query_exec('SELECT * FROM poll_answers');
//        $stmt->execute();
       $poll_answers = mysqli_fetch_assoc($stmt);
   } else {
       die('Poll does not exist.');
   }
   ?>

TTv3 Micro Edition
Ubuntu 20.04.6 LTS Server
Mysql Version: 10.3.39-MariaDB-0ubuntu0.20.04.2
PHP Version: 7.4.3-4ubuntu2.20
Apache Version: Apache/2.4.59 (Ubuntu)
2022-02-20 19:51:26
This mod was completely rewritten last summer, with extended features and rewritten javascript that parses 2 arrays coming out of the ajax file.

I used to have it like this, which just decided which  DIVs to show or not based on a table read. But that contradicted the AJAX feature so now its all combined and updates live.

You can use any db connector/object as long as you retain the SQL you see. After that, it really doesn't matter how its interpreted, as long as the SQL is there it will show up.

Today's version running live, is hired (freelancer.com) work that took 6 hours and now spans data across 3 tables with very specific references and JOINs. Its had a few updates lol


If votes exceed 10, a flag appears and its a running race to the most votes

Is this mod working for you ?

Last edited by STorrents2020 on 2022-02-20 19:57:36
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 9
  • Members: 0
  • Guests online: 9
  • Comments: 3
  • Messages: 1,728