I've to write an long poll query from my database - currently using mysqli. I'm successfully calling the data and return in my javascript code, but, now is the trick part, after 2 minutes, I receive this error: "Uncaught SyntaxError: Unexpected end of input".
I googled and read a couple pages (more then 30 I guess), but I wasn't able to solve this one... everyone says is most likely that I forgot to close some brackets... but I guess not..
In other hand I prefer use json.parse()
than eval()
.. and neither of them is working...
Thank for the attention.
Ps.: I'm not english native speacker, sorry any misspelling;)
That is my current js file
var old_msg_id = "<?php echo $old_msg_id; ?>";
function waitForMsg() {
$.ajax({
type: "GET",
url: "poll.php?old_msg_id=" + old_msg_id,
async: true,
cache: false,
//dataType : 'json',
success: function (dataRespond) {
//var jsonAnswer = eval("(" + dataRespond + ")");
var jsonAnswer = JSON.parse(dataRespond);
if (jsonAnswer.msg !== "") {
alert("New msg added to base!");
console.log(jsonAnswer.msg);
};
old_msg_id = jsonAnswer.old_msg_id;
setTimeout('waitForMsg()', 1000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Deu merda!: Error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()', 15000);
}
});
}
$(document).ready(function () {
waitForMsg();
});
That is my poll.php
error_reporting(0);
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('padova', $conn) or die('Could not select database.');
$result = mysql_query("SELECT id FROM test ORDER BY id DESC LIMIT 1");
if($result === FALSE) {
die(mysql_error());
}
$old_msg_id = $_GET['old_msg_id'];
$result = mysql_query("SELECT id, text FROM test ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
$msg = $row['text'];
}
while($last_msg_id <= $old_msg_id)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT id, text FROM test ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
$msg = $row['text'];
}
}
$response = array();
$response['msg'] = $msg;
$response['old_msg_id'] = $last_msg_id;
$response = array_map('htmlentities',$response);
echo json_encode($response);