Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update different parts of a web page dynamically?

I have a script that updates information of my website, it loads the date from another page every second and with this i can have a clock on my website that updates ever second. However i want to do the same sort of thing but with another part of my website.

This is the code im using so far:

<script type="text/javascript" charset="utf-8">

    $(document).ready(function() 
    {
        $("#myDiv").load("response.php");
        var refreshId = setInterval(function() 
        {
            $("#myDiv").load('time.php');
        }, 1000);
    });

</script>

and then when i was to display the time i use:

 <div id="myDiv"> </div>

So how could i use it on another part of my website? Would it be wise to code the script and change the '#myDiv' to something else like '#myDiv2' or is there another way i could do it in the same script?

I want to know the best practise for this situation.

Thanks for the time.

like image 415
ragebunny Avatar asked Dec 22 '22 03:12

ragebunny


1 Answers

Personally I prefer a more declarative style, so something like

HTML:

<div data-update="newContent.php" data-refresh-interval="500"></div>

Javascript:

$('[data-update]').each(function() {
  var self = $(this);
  var target = self.data('update');   
  var refreshId =  setInterval(function() { self.load(target); }, self.data('refresh-interval'));
});

This approach means that all information to discern page updates lives in the HTML, it then is (hopefully!) easier to reason about pages when you only have to look in the view to figure out what will happen. It also makes it much easier to add functionality to other pages, since applying the same markup is all that is required.

like image 149
Rich O'Kelly Avatar answered Dec 29 '22 13:12

Rich O'Kelly