After a week of googling and search.I am hard to find even a single tutorial about long polling from a database table instead of from a flat text file named data.text. Currently, I write manually anything in data.text and it instantly appears in the browser.
This is the question: Long polling using database? is not answered properly even in StackOverflow. (I found a lot here but in vain.).Example of this is also here filemtime alternative for MySQL
How can I modify getdata.php to make it enable for fetching data from database?
$sql=mysqli_query($database,"SELECT * FROM messages where time>=$curr_date ORDER by time DESC");
while($row=mysqli_fetch_array($sql)){
$messages=$row['messages'];
$id=$row['id'];
echo $messages;
}
Messages table is as follows
id fro to mesg time status last_modified
I am here listing an example. In this example, three files are being used.
- index.html
- getdat.php
- data.text
Is there any need to make a fourth file to get data from database(mysql)? if not, then what type of changes are necessary in the getdata.php or data.text to use dynamic data from database?
Here is my Javascript
<script type="text/javascript" charset="utf-8">
var timestamp = null;
function waitformsg() {
$.ajax({
type:"Post",
url:"getdata.php?timestamp="+timestamp,
async:true,
cache:false,
success:function(data) {
var json = eval('(' + data + ')');
if(json['msg'] != "") {
$("#messages").append(json['msg']);
}
timestamp = json["timestamp"];
setTimeout("waitformsg()", 1000);
},
error:function(XMLhttprequest, textstatus, errorthrown) {
alert("error:" + textstatus + "(" + errorthrown + ")");
setTimeout("waitformsg()", 15000);
}
});
}
$(document).ready(function() {
waitformsg();
});
</script>
Here is the getdata.php file
<?php
include("../model/includes/classes.php");
$filename='data.php';
$lastmodif=isset($_GET['timestamp'])?$_GET['timestamp']:0;
$currentmodif=filemtime($filename);
while($currentmodif<=$lastmodif){
usleep(10000);
clearstatcache();
$currentmodif=filemtime($filename);
}
$response=array();
$response['msg']=file_get_contents($filename);
$response['timestamp']=$currentmodif;
echo json_encode($response);
?>
messages
table. – Allayne