Long-polling in Laravel chat: Why is the div not updating itself?

天大地大妈咪最大 提交于 2019-12-01 10:39:33

From what I see, I think infinite while loop is the problem here.

PHP and Sockets

If you cannot use NodeJS, try out PHP with Sockets. Should work for this pretty well!

Improvements

You said you search for improvements. Here they are.
Plus I would use Angular to bind data retrieved from server to the view.

The view file

<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>

Routes

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'];
}

I think, code is pretty straighforward... Comments should explain everything.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!