Skip to content

Instantly share code, notes, and snippets.

@itommyyang
Last active December 20, 2015 01:19
Show Gist options
  • Save itommyyang/6048032 to your computer and use it in GitHub Desktop.
Save itommyyang/6048032 to your computer and use it in GitHub Desktop.
long polling (php+ajax)
function waitForDisc(){
$.ajax({
type: "POST",
url: "/longpolling.php",
data: "timestamp="+timestamp_d+"&mid="+jt,
async: true,
cache: false,
success: function(feed){
var json = eval('('+feed+')');
//do whatever you want with json
setTimeout('waitForDisc()',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("error: " + textStatus + " (waitForD error" + errorThrown + ")");
setTimeout('waitForDisc()',15000);
}
});
}
<?php
$mid = isset($_POST['mid']) ? $_POST['mid'] : null;
if($mid == null){
echo "error";
}else{
$dir = '/your-customized-directory/';
$filename = $dir.$mid.".txt";
$lastmodif = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
$currentmodif = filemtime($filename);
while($currentmodif <= $lastmodif){
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response['msg'] = get_new_discussion($mid);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment