using ajax readystate 3 polling

This one is not news anymore, but anyway, a friend of mine asked about a function to notify the browser of changes on the backend, so with multiple online users you can notify a user of changes others make.

One way is a socket daemon, the other is using the ajax redystate 3 ‘polling’ feature (a bit like the comet server). As the ajax xhr-object is a basic http-wrapper, it has the same sequence of a normal http connection. A normal call is in readystate 3 (receiving data) until the server signals that was the end of it, readystate 4, where you can pick up the returned http-connection status (200, 404 etc.)

Using the php flush() command inside a running program, you force output to the browser, which triggers a readystate 3 change in an xhr instance. You can pick up on the triggered readystate change and read the new output in the buffer.

A demo is basic, and requires four files

  • queue.txt  (chmod 777)
  • polling.js
  • polling.php
  • polling.html

I put one queue.txt file on the backend with 777 permission so anyone can read and write it.

Then I make a javascript file containing two calls, startclock and stopclock (and makeXmlHttp() to make an xhr instance). Startclock starts an endless loop and outputs the incremental content of the output buffer to a div in the html file (for the demo I echo time(), that way you can make an ajax digital clock) :

function startclock()
{
        var index = 0;            
        xmlHttp = makeXmlHttp();
        
        xmlHttp.onreadystatechange = function()
        {
                if ( xmlHttp.readyState == 3 )
                {
//grab the new part of the output buffer and write it to a div
				var rtlen = xmlHttp.responseText.length;
			        if (index < rtlen) {
			           document.getElementById("seoresult").innerHTML =  xmlHttp.responseText.substring(index);
			           index = rtlen;
			        }
			}
        }
        xmlHttp.open("POST", "polling.php?action=start", true);
        xmlHttp.send('');
}

stopclock() just calls a php function that writes 'stop' in queue.txt :

function stopclock()
{
        xmlHttp = makeXmlHttp();
        xmlHttp.open("POST", "polling.php?action=stop", true);
        xmlHttp.send('');
}

For the sake of the demo, I added a function stopclock() that writes ‘stop’ to the queue.txt.

Then the polling.php program file : this contains a routine that runs an endless loop and three routines for the queue.txt file (write ‘start’, add ‘stop’, and read content). The endless loop reads queue.txt once every half second, if the word ‘stop’ is in there it ends, the php-program ends and the xhr call ends. Otherwise the endlessloop function outputs the time, and flushes the buffer to the browser :

if($_GET['action']=='start') {
	endlessloop();
} else {
        writestop();
}


function endlessloop() {
//truncate the queue, write 'start'
	writestart();

//get the time
	$start=time();

//using while(1) or while(true) you start an endless loop,
//and use break to end it, I tend to also use a timed end,
//to prevent the program from running on endlessly on the
//server if I break the http connection

	while(1) {
//read the file contents
		$the_Text=readsome();

//check if the word 'stop' is in there
//if so, echo a notification, end the program
		if(strpos($the_Text, "stop")>0) { 
			echo 'clock stopped';
			flush();			
			break;
		}

//after 45 seconds (arbitrary) end the program anyway
		if(time()>($start+45)) {
			echo 'time elapsed';
			flush();			
			break;
		}

//echo the time
		echo time();

//wait for a while
		usleep(100000);

//flush triggers a forced dump of the buffer to the browser
		flush();
	}
}

function writestart() {
//truncate the file, write 'start'
	$fhandle =fopen('queue.txt', 'w');
	fwrite($fhandle, 'start');
	fclose($fhandle);
}
function writestop() {
//write 'stop' 
	$fhandle =fopen('queue.txt', 'a');
	fwrite($fhandle, 'stop');
	fclose($fhandle);
}

function readsome() {
//read the file, return the text contents
	$fhandle =fopen('queue.txt', 'r');
	while($buffer = fread($fhandle, 1024)) {
		$text.=$buffer;
	}
	return $text;	
}

If you start the same polling.html in two browser windows you’ll notice that stopping one, also causes the other to stop. Very basic demo.

Posted in php and tagged .

Leave a Reply

Your email address will not be published. Required fields are marked *