0

I know this topic is discussed a lot of, but I don't see perfect execution of it. In this case, I want to get some explanations about it. So, this is simple code:

!DOCTYPE html>
<html>
<head>
<title>Long Poll Example</title>
<script src="jquery-2.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
var timestamp=null;
function waitForMsg(){
$.ajax({
type: "GET",
url: "a2.php?timestamp="+timestamp,
async: true,
cache: false,

success: function(data){
var json=eval('('+data+ ')');
if (json['msg'] !="") {
//alert( json['msg'] );
//Display message here

 $("#msgold").empty();
 $("#msgold").append(json['msg'] +"<hr>").slideDown("slow");

 }
 timestamp =json["timestamp"];
 setTimeout("waitForMsg()",1000);
 },
 error: function(XMLHttpRequest,textStatus,errorThrown) {
 // alert("error: "+textStatus + " "+ errorThrown );
 setTimeout("waitForMsg()",15000);
 }
 });
 }

 $(document).ready(
 function()
 {
 waitForMsg();
 });
 </script>
 </head><body>
 <H3> Server Results </H3>
 <hr />
 <div id="messages"><div id="msgold"></div></div>
 <A href='stream.html'>Another streaming Example Stream.html </a>
 </body>
 </html>



and php::

<?php
//Long Polling
$filename= dirname(__FILE__)."/data.txt";

$lastmodif = isset( $_GET['timestamp'])? $_GET['timestamp']: 0 ;
$currentmodif=filemtime($filename);

while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif =filemtime($filename);
}

$response = array();
$response['msg'] =Date("h:i:s")." ".file_get_contents($filename);
$response['timestamp']= $currentmodif;
echo json_encode($response);



So, this is pretty simple code of execution long-polling comet, but it doesn't work perfectly. It works, if you try to change data.txt file during request time (less then 30 sec or another set_timeout_interval it doesn't matter). But, when this time out, it response an error which isn't catched by javascript code. I was trying to find solution but I couldn't. And I ask you to help me to find the solution of this problem, because in my task the script has to make several requests to server to get neccessary response even if some previous responses were with timeout exeptions.
SOLVED

dmytro
  • 246
  • 8
  • 21

0 Answers0