Here is the jquery code:

$(document).ready(function () { $("#submit").on("click", getRequest); $(document).on("keydown",function (event) { /*при нажатии Enter отправляется сообщение*/ if(event.keyCode == 13){ getRequest(); } }) }); /*Функция которая отправляет данные асинхронно*/ function getRequest() { var date = new Date(); var minutes = date.getMinutes(); if(minutes < 10){ minutes = "0"+minutes; } var json = { /*Данные для передачи */ id:getId()+1, message: $("#message").val(), time:date.getHours()+":"+minutes } /*Строка для вывода на страницу в настоящее время*/ var string = "<div class = 'deserve'><div id = 'name'><p>Антон Томаштик</p></div><div id = 'mess'>"+json.message+"</div><div id = 'time'> "+json.time+"</div><span class='close'></span></div><div class='id' type='hidden'>:"+json.id+"</div>"; if(json.message != ""){ $.ajax({ /* */ url:"mind.php", type:"POST", data: {json:JSON.stringify(json)}, success:function (data) { /*Добавляю строки на дисплей не дожидаясь ответа с сервера*/ $("#display").append(string); $("#message").val(""); } }); }else{ $(".result").html("Сообщение пустует"); } } function getId(){ /*Основная проблема здесь*/ var id; id = document.getElementsByClassName("deserve").lenght; /* id возвращает undefined хотя на экране сообщений много, он их не считает*/ console.log("дисплей не пустой и в нём "+id+" элементов"); return id; } 

Why did I even write the last block with the variable id? In order for each message to have its own id, by which I could delete the same messages. I tried to count them in various ways. But this method did not work either (.getElementsByClassName ()). Next, the request goes to the mind.php file and is written to the file where the messages are stored:

 <?php ################################################################### # Обработка и запись запроса ################################################################### $arr = json_decode($_POST['json'],true); $fileW = fopen("files/message.txt", "a+") or die(); fwrite($fileW, "<div class = 'deserve'><div id = 'name'><p>Антон Томаштик</p></div><div id = 'mess'>".wordwrap(trim($arr["message"]),25)."</div><div id = 'time'> ".$arr["time"]."</div><span class='close'></span></div><div class='kek' type='hidden'>:".$arr['id']."</div>"); fclose($fileW); ################################################################### 

At index.php there is a #display where all these messages are displayed:

 <!DOCTYPE html> <html> <head> <title>Чат</title> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"> <link rel="icon" href="/favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="style/display-style.css"> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body> <div class = "container"> <div id = "display"> <?php ################################################### #Чтение и запись на дисплей ################################################### $fileR = fopen("files/message.txt","r"); while(!feof($fileR)){ echo fgets($fileR); #Блок кода печатает все сообщения на #display } fclose($fileR); ################################################### ?> </div><br> <!-- Поля для ввода и кнопка отправки --> <textarea id="message" cols="50" rows = "3" name="message"></textarea> <input style= "margin-left: 20px;" id="submit" type="button" value="Отправить" name="submit"> </div> <div style="color:white; margin-left: 20px;" class="result"></div> </body> </html> 

I understand that it would be easier with the database, but I would like to understand the essence. And that's what comes out of it: enter image description here

    0