Ud fra hvad jeg ser, tænker jeg uendeligt while
loop er problemet her.
PHP og stik
Hvis du ikke kan bruge NodeJS, så prøv PHP med Sockets. Burde fungere ret godt til dette!
Forbedringer
Du sagde, du søger efter forbedringer. Her er de.
Plus ville jeg bruge Angular til at binde data hentet fra serveren til visningen.
Visningsfilen
<html>
<head>
<title></title>
{{ HTML::script('//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js') }}
<style>
#chat {
width: 300px;
}
#input {
border: 1px solid #ccc;
width: 100%;
height: 30px;
}
#messages {
padding-top: 5px;
}
#messages > div {
background: #eee;
padding: 10px;
margin-bottom: 5px;
border-radius: 4px;
}
</style>
</head>
<body>
<div id="chat">
<input id="input" type="text" name="message" value="">
<div id="messages">
</div>
</div>
<script>
var $messagesWrapper = $('#messages');
// Append message to the wrapper,
// which holds the conversation.
var appendMessage = function(data) {
var message = document.createElement('div');
message.innerHTML = data.body;
message.dataset.created_at = data.created_at;
$messagesWrapper.append(message);
};
// Load messages from the server.
// After request is completed, queue
// another call
var updateMessages = function() {
var lastMessage = $messagesWrapper.find('> div:last-child')[0];
$.ajax({
type: "POST",
url: '{{ url('chat/refresh') }}',
data: {
from: ! lastMessage ? '' : lastMessage.dataset.created_at
},
success: function(messages) {
$.each(messages, function() {
appendMessage(this);
});
},
error: function() {
console.log('Ooops, something happened!');
},
complete: function() {
window.setTimeout(updateMessages, 2000);
},
dataType: 'json'
});
};
// Send message to server.
// Server returns this message and message
// is appended to the conversation.
var sendMessage = function(input) {
if (input.value.trim() === '') { return; }
input.disabled = true;
$.ajax({
type: "POST",
url: '{{ url('/chat') }}',
data: { message: input.value },
success: function(message) {
appendMessage(message);
},
error: function() {
alert('Ooops, something happened!');
},
complete: function() {
input.value = '';
input.disabled = false;
},
dataType: 'json'
});
};
// Send message to the servet on enter
$('#input').on('keypress', function(e) {
// Enter is pressed
if (e.charCode === 13) {
e.preventDefault();
sendMessage(this);
}
});
// Start loop which get messages from server.
updateMessages();
</script>
</body>
</html>
Ruter
Route::post('chat/refresh', function() {
$from = Input::get('from', null);
if (is_null($from)) {
$messages = Message::take(10);
} else {
$messages = Message::where('created_at', '>', $from);
}
return $messages->latest()->get();
});
Route::post('chat', function() {
return Message::create(['body' => Input::get('message')]);
});
Route::get('chat', function() {
return View::make('chat');
});
Model
class Message extends Eloquent
{
protected $fillable = ['body'];
}
Jeg synes, kode er ret ligetil... Kommentarer burde forklare alt.