Originally before I understood long-polling, I had this code:
var updateMessages = function() {
var conv_id = [];
var lastMessages = [];
$('.user').each(function(){
conv_id.push($(this).find('p').attr('id'));
});
if($('.rightP').find('.msg .msg_block').length!=0){
$('.rightP').find('.msg .msg_block').each(function(){
if(($('.rightP').find('.msg .msg_block p').length)==0){
}else {
lastMessages.push($(this).find('p:last-child')[0].dataset.created_at);
}
});
}
$.ajax({
type: "POST",
url: 'create/populate',
data: {
'from': lastMessages,
'conv_id':conv_id
},
success: function(messages) {
console.log(messages);
$.each(messages, function() {
appendMessage(this);
});
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.responseText);
},
complete: function() {
window.setTimeout(updateMessages, 2000);
},
dataType: 'json'
});
};
updateMessages();
However, one person commented that this code isn't long-polling. So I researched and adjusted some codes above like so :
...
complete: function() {
updateMessages(); //also tried updateMessages;
},
timeout:30000,
dataType: 'json'
...
but it ran into problems such as not polling at all and the messages won't update. How can I adjust my original code to do long-polling? Improvement of code is a bonus. Thank you!
gente note : I don't use web sockets bcoz of legacy browser compatibility issues. I also don't use nodejs because my shared-server does not allow long-running processes.
PHP code (in my controller)
public function index()
{
$timestamps = Input::get('from'); //timestamp of latest message
$conv_id = Input::get('conv_id');
$allMessages = Messages::whereIn('conv_id',$conv_id);
if(is_null($timestamps)){
$messages = $allMessages->orderBy('created_at','desc')->take(10);
}else{
asort($timestamps);
$messages = $allMessages->where('created_at','>',end($timestamps));
}
return $messages->get()->reverse();
}