I looked at a brief introduction to ajax long polling here and tried to mimic it on my own pc using wamp, however I have encountered a couple of problems.
I kept getting an error about undefined index in the longpolling.php file, line 29 which is
$num = $_GET['num'];This was because there was one ajax get function that didn't have a num parameter resulting in $_GET not being set. I changed the code to
if(isset($_GET['num'])) $num = $_GET['num']; else $num = "";
and that works fine. However, once i reload the page, the cd count decrements once and then stops.
Would anyone know the reason why this is happening? php file (server)
<?php
$cd_stock = ("CdCount.txt");
function updateStock($num)
{
global $cd_stock;
$count = file($cd_stock);
$count = (int)$count[0];
$count = $count - $num;
if ($count < 0) $count = 0;
$fp = fopen($cd_stock , "w");
fputs($fp , "$count");
fclose($fp);
echo $count;
}
function getCdCount()
{
srand();
$newOrder = rand(1, 3);
$sleeptime = rand(2, 10);
sleep(2);
updateStock($newOrder);
}
if(isset($_GET['num']))
$num = $_GET['num'];
else
$num = "";
if ( $num = "")
{
getCdCount();
}
else
{
updateStock((int)$num);
}
?>
javascript file (client) (uses prototype framework)
Event.observe(window, 'load', function() {
Event.observe( 'btnSubmit', 'click', purchaseCD);
connectToServer();
});
function connectToServer()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'LongPolling.php',
{
method: 'get',
onSuccess: function(transport)
{
if (parseInt(transport.responseText)) connectToServer();
}
});
}
function purchaseCD()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'LongPolling.php',
{
method: 'get',
parameters: { num: $('txtQty').getValue() }
});
}
The html file isn't really worth posting up. it just includes the ajax javascript file and the prototype js file and the relevant divs etc.
I've been racking my brain for hours trying to solve this but I have no idea what is wrong, and it is not encouraging that this is coming from a "tutorial" type article.