Long polling with database data?
I have done something very similar recently. I did use jQuery .ajax call instead of the generic XMLhttprequest but the idea is the same:
recentFunction(container, lastDate){ var lastDate = ""; return $.ajax({ type: "POST", url: "getData.php", cache: false, data: { 'request': 'recent', 'param': lastDate }, dataType: "json", success: function(data){ if(data != null){ $.each(data, function(key, value){ if(key == 0){ lastDate = value['date_added']; } var html = "some html here"; // append html to dom element here // and delete any old items here if needed }); } }, complete: function(){ setTimeout(function(){recentFunction(container, lastDate)}, 7000); } });}
in the getData.php file I have query with a where clause that gets any items from db that are more recent than last element. Default value for $lastDate is set to 0, so it returns all items if no date is submitted.
<?php$lastDate = 0;$recent = array();$recentQuery = "SELECT id, date FROM someTable WHERE date > '" . $lastDate . "'";$recentResults = $db->query($recentQuery);while($r = $recentResults->fetch_array(MYSQLI_ASSOC)){ $recentMovies[] = $r;}echo json_encode($recentMovies);?>