I'm writing a chat application. I would like to know if there are problems in this code.
This function sends message:
function sendMessage()
{
var text = $('#messageBox').val();
$('#messageBox').val('');
if($('.context').scrollTop() + $('.context').innerHeight() >= $('.context')[0].scrollHeight)
{
$(".context").animate({ scrollTop: $('.context')[0].scrollHeight}, 1000);
}
$('.context').append('<div class="inner">'+ text +'</div>');
if(text != '')
{
$('#send').attr('disabled', 'disabled');
$.ajax({
url: 'http://localhost/chat/display',
async: true,
type: "POST",
data: 'text=' + text,
cache: false,
//dataType: 'json',
success: function (msg) {
if (msg == 1)
{
$('#send').removeAttr('disabled');
}
},
error: function (msg) {
alert('app has an error!');
}
});
}
}
When the user sends a message, the message is written on the page before saving.
This code comes before the AJAX call. Is it right?
$('.context').append('<div class="inner">'+ text +'</div>');
This function shows messages:
$(document).ready(function () {
$(window).load(displayMessage(lastTimestamp));
});
function displayMessage(time)
{
$.ajax({
url: 'http://localhost/chat/display',
async: true,
type: "POST",
data: 'time=' + time,
cache: false,
dataType: 'json',
success: function (msg) {
if(msg)
{
if($('.context').scrollTop() + $('.context').innerHeight() >= $('.context')[0].scrollHeight)
{
$(".context").animate({ scrollTop: $('.context')[0].scrollHeight}, 1000);
}
$('.context').append(msg[0]);
time = msg[1];
}
setTimeout(displayMessage, 2000, time);
},
error: function (msg) {
displayMessage(time);
}
});
}
After the page loads, this function will be run to send data to be displayed.
Display method:
public function display()
{
if(isset($_POST['text']))
{
$text = DB::Escape($_POST['text']);
$time = time();
DB::Query("INSERT INTO `messages` (`user_id`, `to_message_id`, `text`, `timestamp`) VALUES ('{$_SESSION['id']}', '1', '{$text}', '{$time}')");
if(DB::AffectedRows() > 0)
{
return 1;
}
else
{
return DB::LastError();
}
}
if(isset($_POST['time']))
{
$time = intval($_POST['time']);
$current = time();
while (time() - $current < 10)
{
$result = self::findAll("WHERE (`timestamp` > '{$time}' AND `user_id` != '{$_SESSION['id']}')");
if(count($result) > 0)
{
$html = '';
foreach ($result as $obj)
{
$html .= '<div class="inner">'. $obj->text .'</div>';
}
return json_encode(array($html, $obj->timestamp));
}
else
{
sleep(3);
}
}
}
}
Note this section:
while (time() - $current < 10)
This code slows sending and receiving messages so it takes several seconds to send and insert a message when I press Enter or click the sending button.
I'm using last timestamp for selecting messages from database. Is there a problem as the same time in timestamp column? I'd like to fix this apparent performance problem.