PHP Real-Time Data Refresh Using Ajax

You can achieve real-time data refreshing in PHP using Ajax technology. Here is a simple example code:

The file index.php:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            setInterval(function(){
                $.ajax({
                    url: 'getData.php',
                    success: function(data){
                        $('#result').html(data);
                    }
                });
            }, 1000);
        });
    </script>
</head>
<body>
    <div id="result"></div>
</body>
</html>

Obtain data from getData.php.

<?php
// 在这里编写获取数据的代码,比如从数据库中查询数据
$data = "实时刷新数据:" . date('Y-m-d H:i:s');

echo $data;
?>

The code above utilizes the jQuery library in the index.php page to make Ajax requests. After the page is loaded, an Ajax request is sent to the getData.php page every 1 second using the setInterval function to retrieve data, which is then displayed in the

on the page.

In getData.php file, code can be written to retrieve data, such as querying data from a database, and then returning the retrieved data to the index.php page.

Please be aware that the example above is just a simple example and may need to be modified and improved according to specific requirements in actual applications.

bannerAds