views:

120

answers:

1

I know this is quite a vague question -- sorry about that. If I have a forum, shoutbox or something similar where users enter and submit data, running on PHP and MySQL, what is the best way to have the newly submitted content automatically display on the page for all users when it is submitted?

Much like a live newsfeed, if you like... The effect sort-of works here at stackoverflow, when you are answering a question you are told when new answer is submitted. I want to test for newly submitted content and then display it automatically.

Any suggestions? Many thanks :)

+2  A: 

Obviously the first thing that springs to mind is a lightweight AJAX request every x seconds to check for new content.

Something along the lines of http://buntin.org/2008/09/23/jquery-polling-plugin/

Edit: This is untested.

AJAX call to http://example.com?lastCheck=1273244156

PHP: 
<?
    if(isset($_GET['lastCheck'])){
        $ts = mysql_real_escape_string($_GET['lastCheck']);

        $result = mysql_query("SELECT * FROM `table` WHERE `timestamp` >= {$ts}");
        $rows = mysql_fetch_array($result, MYSQL_ASSOC);

        if($rows){
            header('Cache-Control: no-cache, must-revalidate');
            header('Content-type: application/json');
            echo json_encode($rows);
        }
    }
?>

Then use jQuery to check if the AJAX response is valid JSON, if so build your items and append them to your container.

Sam
Yeah, that makes sense and would be simple enough I suppose... I could just create a PHP script that jQuery uses to get all of the data again every few seconds. Any other suggestions or actual examples?
Tim
Looking at that sort of script, how would I set it to only update and include the latest / newest submission, rather than adding in the whole lot and what sort of thing would I need to put in my PHP to limit this?Thanks for your help
Tim
That. is. awesome. Cheers dude that's a MASSIVE help! :D
Tim