WebDev WebDev - 2 months ago 14
HTML Question

How do i auto refresh my div class content?

My code is as follows -

<div class="huge">
<?php echo date ("g:i:s A"); ?>
</div>


How do i set
<div class="huge">
to refresh every second?

Answer

Assuming that you need to get the update from the server (noted the PHP code in your original post), there are two things you need to implement:

  1. A Server-Side script (in this case written in PHP) to be requested by the client for fresh data.
  2. A Client-Side javascript to fetch fresh data from the server and update your div.

Let's make an example.

index.php

 <html>
    <head>
        <title>My date updater</title>
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    </head>
    <body>
        <div class="huge"><?php echo date ("g:i:s A"); ?></div>
    </body>
 </html>

Javascript (using jQuery)

setInterval(function(){
   $.ajax({
        url:'loadData.php'
   }).done(
        function(data){
            $('.huge').html(data);
   });
},1000);

loadData.php

<?php echo date ("g:i:s A"); ?>

Initially your page named in this example index.php will load and show the initial date (using a bit of php code inline).

Then the javascript will start to get data from the server (using an ajax request to loadData.php) every second and the div will be updated with the fresh data.

Hope it helps a bit!

P.S: Date and time information can also be fetched using pure javascript code on the client-side, but for some applications the date and time information on the client-side is not reliable enough since it relies on the date and time settings that are set by the client browser.