Hello, there is a question, I have a working chat on PHP and a database on one of the sites, but it is updated only when the page is reloaded, I don’t have Ajax, I want to implement it, but I don’t know how, I figured it out with ajax itself, but I don’t have any idea how to use it, insert the chat php code, tell me how to update the messages without reloading, it is possible to redo the code, it is possible to track a new message in the database, and then run Ajax, I don’t know if you write the code, I will appreciate it.

<?php if (isset($_SESSION['loggeduser']) and $_SESSION['loggeduser']['ban status'] <= 0) { //Берём сообщения с БД $messages = mysqli_query($connection, "SELECT * FROM `chat`"); while ($message = mysqli_fetch_assoc($messages)) { //Пока $messages не опустеет, превращаем в строки, и выводим сообщение в отдельном блоке $messageId = $message['id']; $authorInfo = mysqli_query($connection, "SELECT * FROM `users` WHERE `id` = '".$message['author_id']."' "); $author = mysqli_fetch_assoc($authorInfo); ?> //Пока $authorInfo не опустеет, превращаем в строки, и выводим аву и логин автора сообщения <div class="message row" id="<?php echo $message['id']?>"> <div class="col-xs-2 col-sm-2 col-md-2 col-lg-2 messageLeftPart"> <!--Аватарка автора сообщения в виде фона блока, остальные стили в файле стилей--> <div class="authorAvatar" style="background-image: url(../images/uploaded/avatars/<?php if (empty($author['avatar'])){echo 'default.png';} elseif (!empty($author['avatar'])){echo $author['avatar'];} ?>);"></div> </div> <div class="messageTextAndLogin col-xs-10 col-sm-10 col-md-10 col-lg-10"> <!--Выводим логин автора в виде ссылки сразу на его профиль--> <h4 class="authorLogin"><a href="profile.php?id=<?php echo $author['id']?>"><?php echo $author['login'];?></a></h4> <!--Выводим время отравки сообщения--> <p class="messageTime"><?php echo $message['time']?></p> <!--Выводим текст сообщения--> <p class="messageText"><?php echo $message['text'];?></p> </div> </div> 

Closed due to the fact that the issue is too general for participants Dmitriy Simushev , user207618, aleksandr barakin , Darth , br3t Jul 5 '17 at 19:48 .

Please correct the question so that it describes the specific problem with sufficient detail to determine the appropriate answer. Do not ask a few questions at once. See “How to ask a good question?” For clarification. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • 2
    Webkeets are being used at the present time - Alexey Shimansky

3 answers 3

Chat is certainly better to do on the websocket, but if you say that the chat is already there and you need to improve it. Then I can advise you to look towards ajax long polling, this is a continuous queue of waiting requests. Here is an example:

 <script type="text/javascript"> function mainLoop(){ $.ajax({ url:"handler.php", type:"POST", data:{"id":id}, // Предадим id чата. cahce:false, timeout:30000, // Браузер будет ждать ответ 30 сек, если не получит то цикл перезапустится в error. async:true, success:function(result){ $("#response").html(result); // Получаем результат. setTimeout('mainLoop()',10000); }, error:function(){ setTimeout('mainLoop()',10000); } }); } $(document).ready(function(){ mainLoop(); // Запускаем непрерывный цикл. }) </script> 

And php handler

 <?php set_time_limit(30); if (isset($_SESSION['loggeduser']) and $_SESSION['loggeduser']['ban status'] <= 0) { while(true){ // Делаем вечный цикл. $id = $_POST["id"]; $getMessage=(mysqli_query("SELECT * FROM `chat` WHERE id> '$id' ")); if (mysql_num_rows($getMessage)) { while($row=mysql_fetch_array($getMessage)){ // Готовим сообщение. // Echo чтото там... } flush(); // Очистим буфер exit; // Прерываем цикл. } sleep(2); // Перерыв в 2 секунды. } } 

On the client, we run an eternal cycle of long ajax requests, the client makes a request and waits for 30 seconds for the answer, if the answer did not come, he repeats the request, if he comes, we receive data, update them, but the request is repeated anyway, so we set the constant communication with the server. About ajax long pooling on the Internet you can find a lot of information and examples. And on the server side, we do an eternal loop, where we try to get a message for 2 seconds, if there is a message, then we interrupt the loop and give the data. Instead of a message ID, you can use a time stamp and retrieve a message with a time stamp greater than the initialization mark of the ajax request.

  • Thank you very much for the code, just in php the practice has been and has already become familiar, but in ajax there was no practice, so I’m only learning if I will do this kind of things later I will learn to use these so called sockets - Roma Davidchuk
  • I just don’t understand. You wrote the comment “Let's pass on the chat id,” but I don’t understand what it means, I only have messages and their authors in the id chatRoma Davidchuk
  • Well, Id so, because I do not know the structure of your chat. I just thought that the chat is not one for the whole site, so I passed the id. Here you need to receive only updates, ie only new messages, therefore, I would advise, to transfer the request timestamp and messages from the database to get only the "older" of this label. - Yevhen Bondarenko
  • I’m going to send a valid message sending time, but how can I send it using ajax in the data field? - Roma Davidchuk
  • In js, declare the timestamp variable and pass the date in it. Or it is better if you initialize the chat using an AJAX, you can send an empty timestamp at the first call, set the check in the PHP handler, if the timestamp is empty, return all messages and the last timestamp (though you need to send it in json format) on the client, write this label in the timestamp and give it back, and each time update the label of the last message. To send json echo json_encode($array) for non-client side receiving var res = JSON.parse(data); - Yevhen Bondarenko

In general, it looks like this:

 $("form").submit(function(){ var form=$(this); $.ajax({ method:"post", url:form.attr("action")+"&ajax", data:form.serialize(), cache:false, error:function(){ //do something }, success:function(result){ //do something } }); return false; }); 

PHP processes the data from the form and returns the response from the server back to js

    I work now with chat rooms, I have been studying for a long time. So, if you want to chat with blackjack and real-time and have time to write yourself - take https://socket.io/ or http://socketo.me/
    If the time is less and all sorts of cloud functions like push notifications are needed, your choice is http://parseplatform.org/
    If you have very little time, you need a ready chat with chat rooms and other amenities - take firebase https://firebase.google.com/
    There is a lot of documentation on firebase, ready examples, sdk in all languages, including php https://firebase-php.readthedocs.io/en/latest/
    I hope info was useful.
    PS Ajax for chat - not the best solution