Hello! I am writing a dialogue module between users, the main goal is to not update the page after adding a message so that our text is immediately visible. A sort of analogue dialogue VKontakte. The problem is that I do not know how to implement it. It seems like it was possible to send a message without reloading the page, I get console.log () with Response data, but still, I can't move on. And how can you implement a dialog update? I would appreciate if you help with the code.

Controller

public function sendMessage($id, SendMessageRequest $request) { /** * TODO: Дополнить. Редирект, если диалог с самим собой */ if ($id == Auth::id()) { return redirect('/'); } $conversation = Conversation::whereIn('user_one', [Auth::id(), $id]) ->whereIn('user_two', [$id, Auth::id()]) ->first(); // Получаем данные о беседе /** * Если диалога нет в базе - создаём */ if ($conversation == NULL) { $newConversation = Conversation::create([ 'user_one' => Auth::id(), 'user_two' => $id, ]); } /** * Добавляем сообщение */ Message::create([ 'message' => $request->get('message'), 'user_id' => Auth::id(), 'conversation_id' => $conversation !== NULL ? $conversation->id : $newConversation->id, ]); $response = [ 'status' => 'success', 'msg' => 'Setting created successfully', ]; return Response::json($response); } /** * Переписка с юзером */ public function chat($id) { $user = User::find($id); // Получаем данные юзера $title = 'Диалог с ' . $user->name . ' ' . $user->lastname; // Заголовок страницы /** * TODO: Дополнить. Редирект, если диалог с самим собой */ if ($id == Auth::id()) { return redirect('/'); } $conversation = Conversation::whereIn('user_one', [Auth::id(), $id]) ->whereIn('user_two', [$id, Auth::id()]) ->first(); // Получаем данные диалога $messages = ''; if ($conversation !== NULL) { $messages = Message::where('conversation_id', $conversation->id)->paginate(30); // Загружаем сообщения } return view('mails.chat', [ 'title' => $title, 'conversation' => $conversation, 'messages' => $messages, 'user' => $user, ]); } 

View

 @extends('layouts.app') @section('content') {{-- Самый примитивный вывод сообщений. Обновление, если есть новые сообщения в диалоги + обновление после добавления сообщения --}} @if ($conversation !== NULL && count($messages) !== 0) @foreach($messages as $message) @php($sender = App\User::find($message->user_id)) <div> <b>{{ $sender->name }} {{ $sender->lastname }}</b><br> {{ $message->message }} </div> @endforeach @else <div class="alert alert-info">Нет сообщений.</div> @endif <form id="submit" method="post" action="{{ route('mails.sendMessage', $user->id) }}"> {{ csrf_field() }} <b>Сообщение</b><br> <textarea name="message"></textarea> <button type="submit">Отправить</button> </form> <script> $(function(){ $('#id').on('submit',function(e){ $.ajaxSetup({ header:$('meta[name="_token"]').attr('content') }) e.preventDefault(e); $.ajax({ type:"POST", url:'{{ route('mails.sendMessage', $user->id) }}', data:$(this).serialize(), dataType: 'json', success: function(data){ console.log(data); }, error: function(data){ } }); }); }); </script> @endsection 

1 answer 1

After adding a message to the callback, you can send a list of messages from the controller, and on the page after a successful ajax message sending request, you need to display a list of messages received from the callback