skip to Main Content

I have a script which works fine with echo which it returns a number on a webpage ,but I have to refresh the page to see the updated echo .as in 1, 2, 3, 4, and so on .so what iwould like to know is there away to make this do this every 5 seconds,I only need a echo line to update not the whole reload page though.

I tried the echo method but it only printed it though ,on each page refresh, the idea I’m trying to do is like a digital clock it shows the seconds in real time .but I would like my echo to do 1 ,2,3 and so on via my echo it will display listener:1 and so on

2

Answers


  1. You can use Ajax or Websocket.
    Ajax runs new script on server side every time you call it, but using websocket you can continue running an script on server and get messages as they’re getting ready (for example, like you said, every 5 seconds).

    There’s an example here:
    https://medium.com/@cn007b/super-simple-php-websocket-example-ea2cd5893575

    Login or Signup to reply.
  2. I agree with "maysam besharaty" and the comments on using Ajax. Below is a sample code to achieve this:

    echo_message.php

    <?php
     echo '01';
    ?>
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Update section of page</title>
        <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    </head>
    <body>
    
        <p>Some data here 01</p>
    
        <p id="echo">01</p>
    
        <p>Some data here 02</p>
    
        <script>
            // Function to update the echo message
            function updateEchoMessage() {
                $.ajax({
                    url: 'echo_message.php', 
                    type: 'GET',
                    success: function(data) {
                        // Update the echo message on success
                        $('#echo').text(data);
                    }
                });
            }
    
            // Update the echo message every 5 minutes
            setInterval(updateEchoMessage, 300000); // 300000 milliseconds = 5 minutes
        </script>
    
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search