Hello!) If anyone knows, tell me, please ..

There is a database with messages (guestbook) and the main Message class. On the main page, messages are displayed in descending order of date.

When we add a new message to the database, it is added. A new object of the class Message (I make a request via an AJAX request, I make a return array with returned fields).

But I don’t know how to update the list of messages without rebooting.

 $('form').submit ( function( e ){ e.preventDefault(); $.ajax({ url : 'save1.php', type : 'post', data : $('form').serialize() }).done( function ( data ){ var result = $.parseJSON( data ); $("#block").append( result ); // не работает.. }); }); 

On the main page, messages are displayed using the Меssage:getList and each message is formatted with a div of the block class.

 $arMessages = Message::getList(); while ($row = mysql_fetch_array($arMessages)) { ?> <div id="block" class="w"> <p> <strong>Посетитель : </strong><? echo $row['username'] ?></p> <p><strong> Email : </strong> <? echo $row['email'] ?> </p> <p><strong> Дата добавления : </strong><? echo $row['date'] ?> </p> <p><strong> Сообщение : </strong><? echo $row['msg'] ?> </p> <br /> <button class="j-delete" data-id=" <? echo $row['id'] ?>"></button> </div> 
  • Please show me an example of the server response. In what form the data comes in data (response to the Ajax request) - iKuzko

4 answers 4

In connection with the discussion, I change the previous answer.

 $arMessages = Message::getList(); while ($row = mysql_fetch_array($arMessages)) { ?> <div id="block<?echo $row['id']?>" class="w"> //создаем уникальные id сообщений <p> <strong>Посетитель : </strong><? echo $row['username'] ?></p> <p><strong> Email : </strong> <? echo $row['email'] ?> </p> <p><strong> Дата добавления : </strong><? echo $row['date'] ?> </p> <p><strong> Сообщение : </strong><? echo $row['msg'] ?> </p> <br /> <button class="j-delete" data-id=" <? echo $row['id'] ?>"></button> </div> 

In js

 $('form').submit ( function( e ){ e.preventDefault(); $.ajax({url : 'save1.php', type : 'post', data : $('form').serialize()}).done( function ( data ){ var result = $.parseJSON( data ); var commentline = '<div id="block{id}" class="w"><p><strong>Посетитель :</strong> {username}</p><p><strong>Email :</strong> {email}</p><p><strong>Дата добавления:</strong> {date}</p><p><strong>Сообщение :</strong> {msg}</p></div>'; var html = commentline.replace(/\{id\}/, result.id ).replace(/\{username\}/,result.username).replace(/\{email\}/,result.email).replace(/\{date\}/,result.date).replace(/\{msg\}/,result.msg); $("#msgBlock").preppend( html ); //добавляем элемент в родительский блок. Нужно родителю в котором все комментарии лежат, присвоить id и уже в него вставлять новые сообщения }); }); 
  • Well, yes, and then sit for hours and use foul language looking at absolutely unreadable JS)))) json is good when working with api or really large arrays of homogeneous data, but in the case of outputting 1 message it is much simpler and cleaner to reply with a piece of layout and not bother. it saves both time and nerves .. - Alexander Molofeev
  • already something became clear, thanks)) only here is what $ arMessages = Message :: getList (); while ($ row = mysql_fetch_array ($ arMessages)) {?> <div id = "block" class = "w"> <p> <strong> Visitor: </ strong> <? echo $ row ['username']?> </ p> <p> <strong> Email: </ strong> <? echo $ row ['email']?> </ p> <p> <strong> Date added: </ strong> <? echo $ row ['date']?> </ p> <p> <strong> Message: </ strong> <? echo $ row ['msg']?> </ p> <br /> </ div this is a block in the output loop of the method to get a list of messages .. - Anna
  • one
    That's why you teach the wrong things? Just getting data for such purposes as a message, nickname, id, and accompanying is better in jason. And if we ask for not 1 message, the last 100 messages of the user? Sit and curse the amount of data transmitted? And if we need to correct the conclusion, sit and swear at the impossibility of correcting, how does a piece of html come in? Or then parse it in one place and still work with the data? And if on different pages the same data is used in different ways and do you need a different layout for the blocks? - iKuzko
  • Sorry, the question about "And do not listen to the advice" to return immediately a piece of html "" - what is the bad data method? I think you should not make page markup in js or am I wrong? ... - Barton
  • @Baron, depends on the task. Just do not drive the extra data over the network. After all, some people go to the Internet from smartphones, why do they need extra traffic? If you have data that can be used repeatedly in different combinations - why generate hard frames on the server and give html - then you will not be able to work with this data on the client, you only have a ready piece of code. - iKuzko

Need to use

innerHTML .

Do It

alert (result);

and write what brought

therefore, it does not print, result should contain a text before output, for example, try this

el.innerHTML = '<h1> Cheers </ h1>';

  • tried to do so var el = document.getElementByld ("block"); // where to put el.innerHTML + = result; but without result .. - Anna
  • output object Object - Anna
  • alert (result.username) turned out .. but in this block of code how to add result.username and so on, it’s from index.php $ arMessages = Message :: getList (); while ($ row = mysql_fetch_array ($ arMessages)) {?> <div id = "block" class = "w"> <p> <strong> Visitor: </ strong> <? echo $ row ['username']?> </ p> <p> <strong> Email: </ strong> <? echo $ row ['email']?> </ p> <p> <strong> Date added: </ strong> <? echo $ row ['date']?> </ p> <p> <strong> Message: </ strong> <? echo $ row ['msg']?> </ p> <br /> </ div> - Anna
  • not alert but console.log (result) and look at the result in the console - Barton
 $("#block").preppend( html_data ); // вставит первым 

and from the script of the server that writes the message to the database after processing the request, it is better to immediately return a piece of layout - it is much easier for everyone ...

  • save.php script which saves returns this if ($ newMessage-> save ()) {$ arReturn = array ('username' => $ username, 'email' => $ email, 'msg' => $ msg); echo json_encode ($ arReturn); }; } tried to make var result = $ .parseJSON (data); $ ("# block"). prepend (result); - also nothing happened .. - Anna
  • save.php: if ($ newMessage-> save ()) {?> <div id = "block" class = "w"> <p> <strong> Visitor: </ strong> <? = $ username?> < / p> <p> <strong> Email: </ strong> <? = $ email?> </ p> <p> <strong> Date Added: </ strong> <? = $ date?> </ p> <p> <strong> Message: </ strong> <? = $ msg?> </ p> <br /> <button class = "j-delete" data-id = "<? = $ id?>"> </ button> </ div> <?}?> JS: $ .ajax ({url: 'save1.php', type: 'post', data: $ ('form'). serialize (), success: function (html) {$ ("# block"). append (html);}}); - Alexander Molofeev
  • and something tells me that the #block selector you have is not correct, it turns out that you insert the message into the message and not into the message container - Alexander Molofeev
  • a that returned parseJSON cannot be used ..? it would be better through him .. - Anna
  • it turns out yes .. there is no container .. there is a cyclic output of all messages through the Message: getList method .. I send the resulting array of messages through a loop and draw up each message as a block .. - Anna
 $('form').submit ( function( e ){ e.preventDefault(); $.ajax({ url : 'save1.php', type : 'post', dataType: 'json', data : $('form').serialize(), success: function(result){ if (result.res=='ok'){ $('.list').html(result.html); } else { alert('Error!'); } } }); }); 

In save1.php, perform the necessary actions, according to the logic of the file name, save, then into a variable, for example $ html, form the output string.

 $html = ''; $arMessages = Message::getList(); while ($row = mysql_fetch_array($arMessages)) { $html.=' <div id="block_'.$row["id"].'" class="w"> <p> <strong>Посетитель : </strong>'.$row["username"].'</p> <p><strong> Email : </strong> '.$row["email"].'</p> <p><strong> Дата добавления : </strong>'.$row["date"].'</p> <p><strong> Сообщение : </strong>'.$row["msg"].'</p> <br /> <button class="j-delete" data-id="'.$row["id"].'"></button> </div>'; } echo json_encode(array('res'=>'ok','html'=>$html)); exit; 

And that's all, nothing else is required. Try, it will not work - we will understand.

  • but where is the variable html to declare? can in html add all messages through the loop past ... and then add to it to the beginning html_1 where the div with the new message .. - Anna
  • But I don’t like this approach .. - Anna
  • To declare in save1.php you should have a common block for messages, for example - <div class = "list"> </ div> inside it, blocks with class "w" are added. If you need to add to already existing ones, then you need to write only one block in html and then add the contents of the new block through append to js. $ ('. list'). append (res.html); But the method you have in save1.php as I understand it receives all the messages and not the last one, therefore it would be logical to completely update the block and there’s nothing to add. Slightly corrected the answer, look. - Barton
  • Well, I don’t like it, but writing html in js is nonsense. The scheme of this method is to send a request, save or whatever you’re doing, render new blocks, encode the answer in json and through js replace the contents of the necessary block. Maybe someone will offer another option, the only true there is no) - Barton
  • no, save.php accepts only the last .. - Anna