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 :)
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.
来源:https://stackoverflow.com/questions/2788975/jquery-ajax-load-new-content-when-available