简体   繁体   中英

Refresh page from another (page)

I'm working on a project which contains 2 independent pages: each of them is displayed on a different computer. I would like each time I click on a button on the first page, it refreshes the second page. How can I proceed?

I already tried by stocking a number (1) on a database every time I click on a button. In the second page, if the number is 1 clear it to 0 then refresh. (PHP, jQuery).

I think an answer exists with AJAX but I don't know how to make it.

this is my second page (That I want to refresh)

<script type="text/javascript">
    setInterval("my_function();",10000); 

    function my_function()
    {
        $('.refresh').load(location.href + ' .refresh');
    }
</script>

    <div class="refresh">
        <?php 
            require("database.php");    
            $db = Database::connect();

            $statement = $db->query("SELECT * from refresh");
            $item = $statement->fetch();

            if ($item["value"] =="1")
            {                                   
                $newval = "0";
                $statement = $db->prepare("UPDATE refresh SET value=?");
                $statement->execute(array($newval));
                Database::disconnect();
                header("location: page2.php");
            }
        ?>  
    </div>

Calling your backend on setInterval could be very heavy. WebSockets are made to solve these. You can use WebSockets to achieve what you want in a very lightweight manner.

An implementation for this use case could be (for browser):

var socket = io()

// Send refresh command
document.getElementByd('my-button').addEventListener('click', function () {
  socket.emit('refresh', '')
})

// Refresh when command comes
socket.on('refresh', function() {
  location.reload()
});

You would also need to setup SocketIO on your backend to make all this work. Checkout: http://socketo.me/docs/http

I think one of the best ways is to use Realtime Database which synchronized in realtime to every connected client and your pages automatically receive updates with the newest data.

This way you can have two seprate pages, open in two different tabs ( or computers ) and in one of them, you will update some data in the second page, and it will update & effected automatically.

Personally I like Firebase realtime database and there is a good documentation for each platform that you have plan to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM