Skip to content

Instantly share code, notes, and snippets.

@tathagata
Created January 6, 2012 00:11
Show Gist options
  • Save tathagata/1568119 to your computer and use it in GitHub Desktop.
Save tathagata/1568119 to your computer and use it in GitHub Desktop.
Long Polling using PHP and JQuery
<?php
include 'init.php';
if (!logged_in()){header('Location: index.php'); exit();}
include 'template/header.php';
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript" ></script>
<script src="http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js"></script>
<style type="text/css" media="screen">
.msg{ background:#aaa;padding:.2em; border-bottom:1px #99FF99 solid}
.old{ background-color:#99FFCC;}
.new{ background-color:#A3FFD1;}
.error{ background-color:#992E36;}
</style>
<link rel="stylesheet" type="text/css" href="http://static.flowplayer.org/tools/css/standalone.css"/>
<link rel="stylesheet" type="text/css" href="http://static.flowplayer.org/tools/css/overlay-basic.css"/>
<script type="text/javascript" charset="utf-8">
var lastMessage;
function addmsg(type, data){
var msg = data.substring(0, data.length-5) + "<img id='ajax-loader' src='images/ajax-loader.gif'/><br/>";
console.log(msg);
$("#log").html(msg);
}
function waitForMsg(){
/* This requests the url "msgsrv.php"
When it complete (or errors)*/
$.ajax({
type: "GET",
url: "getprogress.php",
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:500, /* Timeout in ms */
success: function(data){ /* called when request to barge.php completes */
//if(data!=''){
if( data.split('\r\n\r\n')[1] != 'Complete'){
addmsg("new", data);
lastMessage=data;
setTimeout('waitForMsg()',2000);
}else{
console.log(data);
$("#ajax-loader").replaceWith("");
$("#messages").append("<div class='msg new'>Resist has completed. Please wait for the plot.</div>");
//abort();
}
//}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
'waitForMsg()', /* Try again after.. */
"15000"); /* milliseconds (15seconds) */
},
});
};
$(document).ready(function(){
$("#start").show();
$("#messages").hide();
$("button").click(function(){
$("button").hide();
$("#messages").show();
$.post("process.php",{cmd:"start"});
waitForMsg();
});
$("img[rel]").overlay();
});
</script>
<button >Start</button>
<div id="messages">
<div class="msg old">Stated RESIST</div>
<div id='log' class='msg new'></div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment