Php auto refresh page without reloading

To auto refresh a PHP page without reloading, you can use JavaScript or HTML meta tags. Let’s discuss both approaches.

JavaScript Approach:

First, create a PHP file (e.g., “refresh.php”) which will contain the content you want to refresh. In this example, let’s assume we have a file called “content.php” that we want to refresh.

// content.php
<?php
// Your content goes here
?>

Now, in your HTML file or PHP file, you can use the following JavaScript code to refresh the content of “content.php” every few seconds.

<script>
setInterval(function(){
   document.getElementById('refreshDiv').innerHTML = '<?php include("content.php"); ?>';
}, 5000); // Refresh every 5 seconds
</script>

Here, we are using the setInterval function to execute the code inside the function every 5 seconds (5000 milliseconds). Within that function, we are updating the content of a div with the id “refreshDiv” by loading the “content.php” file using the PHP include function.

Make sure to add the following div in your HTML, where you want the refreshed content to appear:

<div id="refreshDiv"></div>

HTML Meta Tags Approach:

Another approach is to use HTML meta tags to refresh the entire page at a specific interval.

<meta http-equiv="refresh" content="5" />

In this example, the content attribute of the meta tag specifies the number of seconds (5 seconds in this case) to wait before refreshing the page. This approach refreshes the entire page, including all PHP content.

Choose the approach that best suits your needs. The JavaScript approach allows you to refresh specific content within a page, whereas the HTML meta tag approach refreshes the entire page.

Leave a comment