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).
ajax, I recommend reading whatREST. - Stepan Kasyanenko