0

I'm sorry if this is already asked. I couldn't find it.

I'm making an AJAX chat system. It's going great, the only problem I'm having is that I need the chat to automatically refresh itself every second. I know this can be done with the load() function...

But I would like to refresh the div and the PHP inside it, now load it from another script. My piece of code(JS):

    <script>   
    setInterval(function() {
    $('#container').load();
    }, 1000); </script>

And the div I want to reload/refresh every second:

<div class="container" id="container">
                  <?php
                  $queryChat    = $mysqli->query("SELECT id,message,username,date FROM chat ORDER BY id DESC LIMIT 0, 10");
                  while($infoChat = $queryChat->fetch_array())
                  {
                  ?>
                    <div class="text">
                        <div class="name"><?php echo $infoChat['username']; ?></div>
                        <div class="time"><?php echo $infoChat['date']; ?></div>
                        <div class="body"><?php echo $infoChat['message']; ?></div>
                    </div>
                  <?php
                  }
                  ?>
                  </div>

And if I do $('#container').load('index.php'); it will give me this(the site will also be very slow): $('#container').load('index.php');

Thank you very much for helping in advance! My English is also very bad due that it's not my mother language :-)

1
  • 2
    Write a script that just returns what should go into #container, and call that with .load() instead of calling the main .index.php. Commented Nov 8, 2014 at 17:22

1 Answer 1

1

Don't you think it will be cleaner to just include() your "message pooling" script inside your <div class="container" id="container">, so that your main chat page will now have:

<div class="container" id="container">
<?php
include("chatScript.php");
?>
</div>

Then chatScript.php will contain:

<?php
    $queryChat    = $mysqli->query("SELECT id,message,username,date FROM chat ORDER BY id DESC LIMIT 0, 10");
    while($infoChat = $queryChat->fetch_array())
    {
    ?>
    <div class="text">
        <div class="name"><?php echo $infoChat['username']; ?></div>
        <div class="time"><?php echo $infoChat['date']; ?></div>
        <div class="body"><?php echo $infoChat['message']; ?></div>
    </div>
    <?php
    }
?>

Then you can simply do

<script>
    setInterval(function() {
    $('#container').load();
    }, 1000); 
</script>

after loading <div class="container" id="container">.

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.