Programmed Under The Influence
Creating a forum/chat room hybrid system

I’ve been asked a few times so far to create a chat room for one of my sites. Now even though I think this is an interesting request, I find that chat rooms have become a thing of the past, which have been taken up by the older Internet crowd and (sadly) cyber-predators (no, not like the one Schwarzenegger fought).

I did some thinking and a friend of mine helped me come up with an idea to create a forum/chat room hybrid. It would have the visual & functional qualities of a forum, but would be updated dynamically using sort of what you now find on Twitter’s real-time search results where you are notified of new posts on a timely basis. I’m not going to go into very much detail cause I had to make it work for my site specifically, but I’ll give you an idea on how it works so you can take it in any direction you want to.

What you’ll need… HTML, PHP, jQuery, and a MySQL database

First thing first, let’s see a quick look at what the HTML code will look like (again, this is really basic). *Note: we are setting a session to keep track of when the user first got to the page so we aren’t loading posts that aren’t “new”:

<?php $_SESSION['last_refresh'] = date('Y-m-d H:i:s'); ?>

<div id="new_posts_msg" style="display: none;"> </div>
<div id="forum_posts">
    <div class="forum_post">First!</div>
    <div class="forum_post">Second post!</div>
    <div class="forum_post">Third!</div>
</div>

Next, we need to set up a timer that will kick off the update function (which fires when the document is ready) and have it run every so often (mine fires every 20 seconds):

$(document).ready(function() {
    setTimeout('checkForNewPosts()', 20000);
}

Now let’s take a look at the function that will call a background script to check for new posts and display a button telling the user that there are new posts:

function checkForNewPosts() {
    $.post('checkForNewPosts.php',
        function(data) {
            if (data > 0) {
	        $('#new_posts_msg')
                .html('<button type="button" onclick="loadNewPosts()">
                  New posts! Click to load them.</button>')
                .fadeIn('slow');
	    }
        });
    
    // Check again in 20 seconds
    setTimeout('checkForNewPosts()', 20000);
}

Let’s take a look at what’s happening on the “back-end” (or the checkForNewPosts.php file). Using the session we set from last time, we will select any “new” posts that weren’t loaded when the page was first loaded. The result is then sent back to the javascript function to display the “new post” notification button if any new posts have been added:

<?php // check for new posts in our `forum_posts` table
    $query = "SELECT COUNT(*) AS new_post_count
        FROM forum_posts
        WHERE forum_posts.added
          BETWEEN '" . $_SESSION['last_refresh'] . "' AND NOW()";
    $result = $this->query($query);
    
    // Return to display notification
    echo $result[0]['alias']['new_post_count'];
?>

If you noticed before, the “new post” notification button had an onclick function called loadNewPosts(). This is shown below and is used to load all the new posts that were found:

function loadNewPosts() {
    $.post('loadNewPosts.php',
        function(data) {
            $('#new_posts_msg').html('').hide(); // Hide the button
            
            // Display new posts
            $('#forum_posts').find('.forum_post:last').after(data);
        });
}

Finally, the loadNewPosts.php file is responsible for retrieving all the new posts and adding them after the latest post already loaded:

<?php
    $query = "SELECT *
        FROM forum_posts
        WHERE forum_posts.added
          BETWEEN '" . $_SESSION['last_refresh'] . "' AND NOW()";
    $result = $this->query($query);
    
    $new_posts = "";
    foreach ($result as $row) {
        $new_posts .= "<div class="forum_post">" .
            $row['forum_posts']['post'] .
            </div>";
    }
    
    // Return to display new posts on web page
    echo $new_posts;
?>

I hope that all made sense and helps you in your endeavors to make a dynamically-tubular website. For a working demo, please check out an active thread at: One Line Rhyme :: Forums

Run out of options? No problem, click &#8216;Another Option?&#8217;
This jQuery plugin lets you easily create new fields with the click of a button (granted you are okay with using &lt;table&gt;s.) It&#8217;s easy to integrate and fairly customizable.
Appendo courtesy of Deep Liquid

Run out of options? No problem, click ‘Another Option?’

This jQuery plugin lets you easily create new fields with the click of a button (granted you are okay with using <table>s.) It’s easy to integrate and fairly customizable.

Appendo courtesy of Deep Liquid

Finishing up the survey voting and results pages.

Basically this is what the site will be about. Surveying decisions that you and your friends have to make on a daily basis. What movie should we go to? Where should we eat? What types of food should we bring to a get-together?

Commenting… you’re doing it right :D

These are two examples of my new commenting system:

  • What!? No Way! (in alpha)
  • Pollacio.us (coming shortly)
Posting checkbox values with PHP and jQuery

For some time I had trouble figuring out how to post checkbox results using jQuery’s $.post function after submitting a form. I searched many different sites finding pieces of the a solution that would fit my needs.
Anyway here’s what I got:

1) Let’s create a simple form.

    <form id="my_form" onsubmit="return processForm()">
        1) <input type="checkbox" class="option" name="options[]" value="1" /><br />
        2) <input type="checkbox" class="option" name="options[]" value="2" /><br />
        3) <input type="checkbox" class="option" name="options[]" value="3" /><br />
        <input type="submit" value="Submit" />
    </form>

2) Create the javascript to handle the form submission.

    function processForm() {
        var options = $('#my_form :input.option');
        var option_array = new Array();
        
        $.each(options, function(index, element) {
            if ($(element).is(':checked')) {
                option_array.push($(element).val());
            }
    
        // Post options to action file
        $.post('/your/path/to/action/file.php', {'options[]': option_array});
        
        return false;
    }

3) Handle the form submission using PHP.

    <?php
        foreach ($_POST['options'] as $option) {
            /* Do whatever you want with your options here. */
        }
        
        // Or you can just print the results to the screen for test purposes
        print_r($_POST);
        exit;
    ?>