Im using a similar script as described here: long-polling info from mysql not working on my website, its work but, when i either refresh the page or click a different link i get an error alert+the website starts lagging seriously, can some one tell me what is causing this?
my code:
$oldIDq = mysql_query("SELECT * FROM messages ORDER BY id DESC LIMIT 1");
while($oldrow = mysql_fetch_array($oldIDq)){
$oldID = $oldrow['id'];
}
$func = '
var oldID = '.$oldID.';
function wait() {
$.ajax({
type: "GET",
url: "../scripts/msg_scripts/msg.php?oldid=" + oldID,
async: true,
cache: false,
success: function (data){
var json = eval(\'(\' + data + \')\');
if (json[\'msg_content\'] != "") {
alert("new meassage added");
}
oldID = json[\'oldID\'];
setTimeout(\'wait()\',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("error: " + textStatus + "(" + errorThrown + ")");
setTimeout(\'wait()\',15000);
}
});
}
$(document).ready(function(){
wait();
});
';
server:
<?php
session_start();
$connect = mysql_connect ("localhost", "root", "")
or die ("couldnt connect");
mysql_select_db ("***") or die ("not found"); //if db was not found die
mysql_query("SET NAMES 'utf8'");
$oldID = $_GET['oldid'];
$result = mysql_query("SELECT id FROM messages ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
}
while($last_msg_id <= $oldID)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT id FROM messages ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
}
}
$response = array();
$response['msg'] = 'new';
$response['oldID'] = $last_msg_id;
echo json_encode($response);
?>
proplem in here in $_GET['oldid'] when you click on another link or refresh the page without it the variable $oldID will be empty and the sql will fail. and the js function keep calling itself with nothing changed every time an error accured and the ajax will keep calling keep failing wich will result to an infinite loop that will hang your site and i guess if you check it on firebug you will see that happening.
dont now if that what you mean hope it help