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 Shoutbox (PDO/jQuery)
You don't have permission for this action!
Controls ·  Search New posts · Mark unread

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

2020-05-05 04:34:08
Here I have today what I rewrote from ground up, no longer using any existing code, previously was shout.php but as AJAX took off in the quest to replace that old bugger, I've brought the script up to speed.
No SQL is changed or needed, it uses the existing tables as they are, so hold on to existing shout data so you get a better view of the mod first impression.

So I didn't know where to go for instructions for adding in the markup for stock V3, so I'll leave that up to you. You know your theme.

[color=rgb(226, 80, 65)]* Be sure to update database details in both AJAX scripts in [/color][color=rgb(226, 80, 65)]/ajax/[/color]

Open /themes/default/header.php and add:


<!-- jQuery.min 1.11.1 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- jQuery.Timeago 1.6.7 -->
<script src="<?php echo $site_config["SITEURL"]; ?>/themes/js/jquery-timeago-1.6.7/jquery.timeago.js"></script>

<!-- CodyHouse Forms Plugin -->
<link rel="stylesheet" href="<?php echo $site_config["SITEURL"]; ?>/js/codyhouse-forms/js/css/reset.css"> <!-- CSS reset -->
<link rel="stylesheet" href="<?php echo $site_config["SITEURL"]; ?>/js/codyhouse-forms/css/style.css"> <!-- Resource style -->
<script src="<?php echo $site_config["SITEURL"]; ?>/js/codyhouse-forms/js/modernizr.js"></script> <!-- Modernizr -->

<script>
function fetchNewShouts() {
   $(document).ready(function () {
       $.ajax({
           url: "/ajax/ajax_shoutbox_get.php",
           method: "GET",
           dataType: 'JSON',
           success: function (data) {
               var html_to_append = '';
               $.each(data, function (i, item) {
                   html_to_append +=
                       '<div class="shoutbox-container"><span class="shoutDate">' +
                       jQuery.timeago(item.date) +
                       ' <span style="color:#b3b3b3">ago</span></span><span class="shoutUser"><img src="' +
                       item.avatar +
                       '" class="shout-avatar" /></span><span class="shoutText">' +
                       item.message +
                       '</span></div><br>';
               });
               $("#shoutbox").html(html_to_append);
               $(".shoutbox-container").filter(function () {
                   return $(this).children().length == 3;
               }).filter(':odd').addClass('shoutbox_alt');
               $(".shoutbox-container").each(function () {
                   $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
               });

           }
       });
   });
}
fetchNewShouts();
setInterval(function () {
   fetchNewShouts()
}, 10000);

// AJAX Shoutbox - POST
$(document).ready(function (e) {
   $("#form-shoutbox").on('submit', (function (e) {
       e.preventDefault();
       $.ajax({
           url: "/ajax/ajax_shoutbox_post.php",
           type: "POST",
           data: new FormData(this),
           contentType: false,
           cache: false,
           processData: false,
           beforeSend: function () {
               $("#posting").html("Posting...").delay(3000).fadeIn().delay(4000).fadeOut();
               $("#posting").fadeIn();
               $("#err").fadeOut();
           },
           success: function (data) {
               if (data == 'invalid') {
                   // Invalid data
                   $("#err").html("Invalid data").fadeIn();
               } else {
                   // Update shoutbox posts after post
                   $("#refresh-posts").html(data).fadeIn(); // Update element
                   $("#posting").html("Posted!").delay(2000).fadeIn().delay(1000).fadeOut();
               }
           },
           error: function (e) {
               $("#err").html(e).fadeIn();
           }
       });
   }));
});
$('.shoutbox-input').keypress(function (e) {
   //e.preventDefault();
   if (e.which == 13) {
       $('#form-shoutbox').submit();
       $("#form-shoutbox")[0].reset();
       return false;
   }
});
</script>


Open /themes/default/theme.css and add:


.shoutbox-container:nth-child(odd) { /* CSS-way of row backgrounds, no plugin needed ;) */
   margin-top: -10px;
   padding-top:3px
}
.shoutbox-container:nth-child(odd) { /* CSS-way of row backgrounds, no plugin needed ;) */
   margin-bottom: -12px;
}
.shoutDate, .shoutEdit, .shoutUser, .shoutText {
   display: table-cell;
   padding-top: 3px;
   padding-left: 20px;
   text-align: left;
   vertical-align: middle
}
.shoutText {
   width: 533px /* layout fix */
}
.shoutAlt {
   background: #FFF;
   padding: 5px
}
.shoutbox_alt {
   background: #ECECEC
}
.shoutbox_noalt {
   background: #FFF;
}
.shout-avatar {
   width: 45px;
   height: 45px;
   border-radius: 50%
}
.shoutbox-form-container {
   padding: 7px;
   width: 70%;
   position: relative
}
.response {
   padding-top: 11px
}


Create /ajax/ajax_shoutbox_post.php


<?php
// AJAX Shoutbox - POST
$dbHost     = "localhost";
$dbUsername = "username";
$dbPassword = "password";
$dbName     = "database";
if (isset($_POST['message'], $_POST['id'])) {
   $username = $_POST['username'];
   $userid   = $_POST['id'];
   $message  = $_POST['message'];
   $sql      = 'INSERT INTO shoutbox (msgid, user, message, date, userid) ';
   $sql .= ' VALUES (NULL, :username, :message, NOW(), :userid)';
   try {
       $db = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8", $dbUsername, $dbPassword);
       $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // Prevent advanced injection by disabling emulated prepared statements
       $query = $db->prepare($sql);
       $query->bindValue(':username', $username, PDO::PARAM_STR);
       $query->bindValue(':userid', $userid, PDO::PARAM_STR);
       $query->bindValue(':message', $message, PDO::PARAM_STR);
       if ($query->execute()) {
           //echo "test";
       }
       die();
   }
   catch (Exception $e) {
       echo $e->getMessage();
   }
}
?>


Create /ajax/ajax_shoutbox_get.php


<?php
// AJAX Shoutbox - GET
$dbHost     = "localhost";
$dbUsername = "username";
$dbPassword = "password";
$dbName     = "database";
try {
   $conn = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8", $dbUsername, $dbPassword);
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // Prevent advanced injection by disabling emulated prepared statements
}
catch (PDOException $e) {
   die('Unable to connect to database');
}
$limit = 6;
$stmt = $conn->prepare("SELECT shoutbox.msgid, shoutbox.userid, shoutbox.user, shoutbox.message, shoutbox.date, users.avatar FROM shoutbox LEFT JOIN users ON shoutbox.user = users.username ORDER BY msgid DESC LIMIT :datalimit");
$stmt->bindParam(":datalimit", $limit, PDO::PARAM_INT);
$stmt->execute();
$userData = array();
if ($stmt->rowCount() > 0) {
   $usersactive = $stmt->fetchAll(PDO::FETCH_ASSOC);
   foreach ($usersactive as $row => $data) {
       $data['id']            = $row['msgid'];
       $data['value']      = $row['message'];
       $data['avatar']    = $row['avatar'];
       $data['user']       = $row['user'];
       $data['userid']    = $row['userid'];
       $data['date']       = $row['date'];
       array_push($userData, $usersactive);
   }
}
echo json_encode($usersactive, JSON_UNESCAPED_SLASHES);
?>


Now upload jQuery.timeago.js from ZIP to /themes/default/js/

This is the HTML block. You can add this anywhere on your site.


<div id="shoutbox" class="response"></div>

<div class="shoutbox-form-container">

   <form class="cd-form floating-labels" name="shoutboxform" id="form-shoutbox" action="/ajax/ajax_shoutbox_post.php" method="post">
       <label class="cd-label" for="shout-label">
           <i class="material-icons" style="color:rgba(46,168,4,1);vertical-align:middle">textsms</i> @
           <span style="color:#252525;font-size:22px" id="posting"><? echo $site_config['SITENAME']; ?></span>
       </label>

       <input type="text" class="shoutbox-input" name="message" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" id="shout-label" placeholder="Type something..." maxlength="200" style="height:4px;font-size:16px" />
       <div style="position:absolute;bottom:25px;left:280px">
           <a href="javascript:PopMoreSmiles();"><img src="/images/smilies/grin.png" style="vertical-align:middle;margin-left:10px" /></a>
           <a href="javascript:PopMoreSmiles();"><img src="/images/smilies/razz.png" style="vertical-align:middle;margin-left:10px" /></a>
           <a href="javascript:PopMoreSmiles();"><img src="/images/smilies/confused.png" style="vertical-align:middle;margin-left:10px" /></a>
           <a href="javascript:PopMoreSmiles();"><img src="/images/smilies/cool.png" style="vertical-align:middle;margin-left:10px" /></a>
           <a href="javascript:PopMoreSmiles();"><img src="/images/smilies/grin.png" style="vertical-align:middle;margin-left:10px" /></a>
       </div>
       <input type="hidden" name="id" value="<? echo $CURUSER[" id "]; ?>" required />
       <input type="hidden" name="username" value="<? echo $CURUSER[" username "]; ?>" required />

   </form>

</div>


That's it, enjoy!

[ATTACH type="full" width="633px" alt="ST-AJAX-Shoutbox.png"]5493[/ATTACH]

It auto refreshes every 10 seconds dynamically. You won't even notice. Press ENTER to post.
ST-AJAX-Shoutbox.png
ST-AJAX-Shoutbox.png
ST-AJAX-Shoutbox-JS.zip
Download
2020-05-05 05:15:46
It's in a template format for views in controllers :love:
Code looks great m8 I'll test this morning  (y)
2020-05-05 06:14:23
no errors in log which is a good sign but not displaying right, inputs are just empty pages
seems around this
<div id="shoutbox" class="response"></div>
[ATTACH type="full"]5494[/ATTACH]

thought it might be paths but i see you used absolute paths for js did you come across this in development
Untitled.png
Untitled.png
2020-05-05 08:19:01
"m-jay, post: 68509, member: 20288":

no errors in log which is a good sign but not displaying right, inputs are just empty pages
seems around this
<div id="shoutbox" class="response"></div>
[ATTACH type="full" alt="Untitled.png"]5494[/ATTACH]

thought it might be paths but i see you used absolute paths for js did you come across this in development


Sorry, my mistake. I use [color=rgb(226, 80, 65)]height: 4px[/color] due to a responsive form plugin that acts up.

In HTML find:
<input type="text" class="shoutbox-input" name="message" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" id="shout-label" placeholder="Type something here..." maxlength="150" style="height:4px;font-size:16px" />


Replace with:
<input type="text" class="shoutbox-input" name="message" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" id="shout-label" placeholder="Type something here..." maxlength="150" style="font-size:16px" />


So how it works, is the AJAX call retrieves [color=rgb(0, 168, 133)]item.[/color][color=rgb(226, 80, 65)]<value>[/color] as objects through JSON array, if you go to url directly you can see the array data, this makes it really easy to test what is coming in from the database or not, and you use them line by line as you have set in the php script, which attaches to the DIV response class, and so their objects that are wrapped in span tags, you can use any HTML in there as long as you use the right line formatting for items like

html_to_append +=
                       [color=rgb(226, 80, 65)]'[/color]<div>Maybe text here</div>[color=rgb(226, 80, 65)]' +[/color]
                       [color=rgb(41, 105, 176)]item[/color][color=rgb(226, 80, 65)].date[/color][color=rgb(41, 105, 176)] +[/color]
                      [color=rgb(226, 80, 65)]'[/color]<div>More HTML</div>[color=rgb(226, 80, 65)]' +[/color]
[color=rgb(41, 105, 176)]                       item[/color][color=rgb(226, 80, 65)].avatar[/color][color=rgb(41, 105, 176)] + [/color]


And whatever is going on in there will be output to
<div id="shoutbox" class="response"></div>


You can plug any object in as long as you've set it up in the PHP script (query & bindvalues)
2020-05-05 12:49:43
is this important js/codyhouse-forms,  still having display problems i can post into database ok just cant see the container
2020-05-05 21:21:30
You don’t need it, It just looks good. Completely optional. Just adjust your field input style, that should do it
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: 8
  • Members: 0
  • Guests online: 8
  • Comments: 3
  • Messages: 1,728