1

I'm working on improving my chat script using jQuery to display and autoscroll the messages. It already works pretty good, but I want to get rid of the 'refresh' effect when replacing the 'div' with updated content from the JSON object, which gets encoded from a PHP array containing the messages with every jQuery request.

How can I achieve this?

This is what works now for me:

<head>
  <script>
    $(document).ready(function(){
      $.ajaxSetup({cache:false});
      $("a").click(function(){
        $("div").empty(); // removing this will get rid of the 'refresh' effect, but it endlessly appends the message log

        $.getJSON('ajax.php', function(data){
          $.each(data, function(i, field){
            $("div").append(field + "<br>");
          });
          $(document).scrollTop($(document).height());
        });
      });
    });

    window.onload = function() {
      document.getElementsByClassName("refreshB")[0].click();
    };

    var intervalID = window.setInterval(refresh, 10000);

    function refresh() {
      document.getElementsByClassName("refreshB")[0].click();
    }
  </script>
</head>

<body>
  <a class="refreshB"></a>
  <div></div>
</body>
DunDev
  • 210
  • 2
  • 13
L. S.
  • 11
  • 3
  • I dont see PHP Code – Manuel Mannhardt Nov 14 '17 at 14:10
  • i assume then that you are retreiving the full conversation each time? I would recommend splitting the entries by time, and getting only the new ones.. but that means changing substantial part of the code. The alternative is comparing, which will make your code even slower – Kaddath Nov 14 '17 at 14:12
  • Your PHP will have to decide what is "new" content that needs to be sent to the browser. As it is currently designed, your JS has no idea what's old and what's new; it simply replaces everything in the chat window with whatever the PHP sends along – WillardSolutions Nov 14 '17 at 14:13
  • smells like a homework assignment – Glubus Nov 14 '17 at 14:14
  • Simply move the `$('div').empty()` to the xhr success callback, that eliminates the time between request and response and will look like an instant repaint – giorgio Nov 14 '17 at 14:18
  • refer this - https://stackoverflow.com/questions/18490026/refresh-reload-the-content-in-div-using-jquery-ajax https://stackoverflow.com/questions/18490026/refresh-reload-the-content-in-div-using-jquery-ajax – Tushar Walzade Nov 14 '17 at 14:19
  • How to compare the entries? – L. S. Nov 14 '17 at 14:19
  • @giorgio Where is the xhr success callback? – L. S. Nov 14 '17 at 14:22
  • The `function(data) { ... }` part, which will get called when the ajax (=xhr) response is received – giorgio Nov 14 '17 at 14:25

1 Answers1

0

First of all you must get only new rows from db.

add new column to table (for example readed) then every time update this column to know which data is new

and you won't need this $("div").empty();