I need advice on how to properly update html after sending an ajax request.
Suppose there is a regular page with comments. On the server, when a page is requested, a request is sent to the database for all comments. A rough example:

$query = mysqli_query($link, "SELECT * FROM Comments WHERE page_id = 2"); if (mysqli_num_rows($query) > 0) { while ($data = mysqli_fetch_assoc($query)) { $render . = "<div class="comment-row"><h3>{$data['author']}</h3><p>{$data['message']}</p></div>" } echo $render; } 

This is the initial page rendering. There is a comment submission form that is sent via ajax.

 $.ajax({ url: 'comment.php', data: data, //здесь данные из формы собранные с помощью FormData(); type: 'post', contentType: false, processData: false, }).done(function (data){ ... //делаем что-то с отрисовкой. }); 

On the server, these data are captured, the data is put in the database and the question is, how to update the html correctly after adding? The most banal option, just leave a simple form without ajax, but I want speakers.
Option 1:
On the server, we put in the infu database and after a successful procedure, we return the json parameters that were just sent by the form:
test.php

 ... mysqli_query($link, "INSERT INTO Comments (author, message) VALUES ('{$_POST['author']}', '{$_POST['message']}')"); exit(json_encode([$_POST['author'], $_POST['message']])); 

customer

 ...//ajax .done(function (data){ data = JSON.parse(data); let firstComment = $('.comment-row:first'); firstComment.before(`<div class="comment-row"><h3>${data.author}</h3><p>${data.message}</p></div>`); }); 

Thus, we do not seem to be generating the extra html code on the server, but we are shifting the whole thing to the client freeing the server.
Option 2:
Approximately the same, but instead of giving json, we give the finished html of the new post with a comment.
test.php

 ... $data = "<div class="comment-row"><h3>{$_POST['author']}</h3><p>{$_POST['messge']}</p></div>"; exit($data); 

Customer

 ... .done(function (data){ $('.comment-row:first').before(data); }); 

Option 3:
We do not steam and just request all the comments from the database and give them entirely:
test.php

 ... //выбираем из бд все комменты после вставки нового $comments = ''; while ($data = mysqli_fetch_assoc($query)) { $comments .= "<div class=\"comment-row\"><h3>{$data['author']}</h3><p>{$data['message']}</p></div>" } exit($comments); 

Customer

 ... $('#container-comments').html(data); 

Option 4
Absolutely no steam and just reload the page. After restarting the original script, we get all the comments, but why then ajax at all?

Actually which option is now used and is the most correct? Maybe I'm missing something and is there a better solution?
All code is written purely for example and general clarity, so there are no checks for incoming data on SQL injections and other vulnerabilities in favor of the brevity of the example.

UPD: The project in which the question is asked is a kind of social network, with the possibility of placing ads, creating groups (similar to VK groups), having a user profile with the ability to create photo albums, document repository and the ability to exchange personal messages between registered participants. (Regarding the question about comments - comments can be left in announcements, groups and other similar functions of the project, and commenting is supposed to be attached to photos or documents. Based on this, besides comments with ajax form submission, you can also add new announcements / groups / records / messages).

  • one
    Option 1 is very good. Approaching the ideal, in terms of SPA. If you want to work with ajax , I recommend reading what REST . - Stepan Kasyanenko
  • one
    And so that you do not duplicate the code that creates html markup comments, you must also request all comments through ajax. - Stepan Kasyanenko
  • @StepanKasyanenko Thanks for the reply! But can be a little more detail? I understand from the point of view of working with php that the initial content is given by the server, as I showed at the beginning of the question, but how to make it a request via ajax and why do I need REST? As far as I know with the help of REST they write APIs referring to different routes. Do you mean to make a web application of the REST type, where each request will be given the same JSON data packet, which will already be used by the JS to generate the layout? A kind of first option from the question, but global. - krown_loki
  • one
    In principle, you are right, yes. I thought here that it is difficult to give an objective answer to the crabs of the whole project. Within your question, Option 1 is good. But Option 2 has an advantage in terms of the lack of code duplication. You can add a question with information about the project: what is it for, at what stage, what technologies are used. Then it will be possible to give a longer objective answer. - Stepan Kasyanenko
  • @StepanKasyanenko Updated the question - krown_loki

1 answer 1

On the page we save time when we last updated the data.

On the server, we implement a method that returns an array of messages that were created or updated after the requested time.

This method can be called by timer and always after sending / changing your message.

  • Do not tell me how to keep the update time on the page? For several blocks of this kind (if we admit there are not only comments) will it be necessary to store several time stamps? And if you call a similar method on a timer, it will inevitably once every few seconds (depending on the timer) peck the server and, in particular, the database for updates. In my opinion this is not very good. Correct if I'm wrong. - krown_loki
  • About the timer - I agree, now there are other methods. You can store time either in a hidden field of the same form that the text itself is sending, or simply in a JavaScript variable - Herman Borisov