-3

I want to create a little chat with PHP. Everything works fine but the chat doesn't reload automatically. Is there a function that would solve my problem?

My PHP-Code:

<?php
  $newmsg= mysqli_query($db_chat, "SELECT msg, username, time FROM messages");
  while($row = mysqli_fetch_object($newmsg))
  {
      echo '<div class="messagesinchat">';
        if ($row->username == "admin") {
          echo '<div class="ownmsg">';
          echo $row->username. ":&nbsp " . $row->msg;
          echo "<br />";
          echo '</div>';
        }
        else{
          echo $row->username. ":&nbsp" . $row->msg;
          echo "<br />";
        }
      echo '</div>';
  }
    ?>
User987123
  • 97
  • 1
  • 11

3 Answers3

0

You can do a page reload after a few seconds as per your need.

<script>
 setTimeout(function(){
  window.location.reload(1);
 }, 5000);
</script>

or

<meta http-equiv="refresh" content="5; URL=http://yoursite.com/chat.php">
Azeez Kallayi
  • 2,567
  • 1
  • 15
  • 19
0

You can do it with PHP:

header("Refresh:0");

See Peter Mortensen's answer on stack overflow here

Community
  • 1
  • 1
SH_
  • 266
  • 2
  • 3
  • 17
0

You need to define your div in your display page, and, you could use jQuery's .load() to load the chat messages into the div using a PHP script. Then, every x seconds, reload your div.

Let's say you have:
display.php to actually, well.. display your chat. (<div id='messagesinchat> should be here.

In display.php, have the jQuery like:

$(function() {
    setInterval(function() {
        $('#messagesinchat').load('chat.php?action=show');
    }, 1000);
});

In chat.php?action=show you execute the queries to search and print your messages.

Condorcho
  • 503
  • 4
  • 12