Here, there is such a javascript code:

function updateChat(){ $.ajax({ url : "http://localhost/kiosl/rooms/default/protected/models/chat-server.php", type : "get", data : "last_displayed_chat_id="+$('#last_displayed_chat_id').val(), dataType : "json", success : function(response , status , http){ $.each(response, function(index,item){ document.getElementById("kiosl_chat_box").innerHTML += "<li class='friend'> <div class='friend-msg-wrap'> <img class='user-img img-circle block pull-left' src='../dist/img/user.png' alt='user'/> <div class='msg pull-left'> <p>" + item.user_comment +"</p> <div class='msg-per-detail text-right'> <span class='msg-time txt-grey'>" + item.user_name + "</span> </div> </div> <div class='clearfix'></div> </div> </li>"; }); }, error : function(http, status, error){ alert('Some Error occured : '+error); } }); } updateChat(); setInterval(updateChat, 1000); 

And that's the problem: every time in kiosl_chat_box for 1 sec. html code is added:

<li> Бла Бла бла </li>

Question: how to make that the repeating code would not be added.

PS My javascript experience is already divided by 0.

  • Something I do not understand what you have a problem. You yourself launched a command to call the updateChat() function every second. - JamesJGoodwin
  • @JamesJGoodwin, the problem is that in the source script, after the "success" there was this: $ .each (response, function (index, item) {$ ('# chat_box'). Val ($ ('# chat_box'). val () + item.user_name + ':' + item.user_comment + '\ n'); $ ('# last_displayed_chat_id'). val (item.chat_id); And there was no such problem. But there the data was sent to textarea. And I need them to go to the div for design. In a word: I make a chat, and if you have a good script for real-time chat (without frameworks), then pliz - LabondK

1 answer 1

The problem is that the .val() function causes the replacement of all content in the textarea. That is, equals operator = . In the current code, you use the += operator, that is, an assignment operator, which adds content to a page to already existing content. Simply put, adds content. You can solve this problem by making PHP give you only new messages, not all at once. Frankly, PHP is not very suitable for solving this problem. You need to google in the direction of long-poll requests and sockets, or switch to NodeJS.