tags:

views:

2146

answers:

2

I'm delving into some AJAX and I'm trying to utilise jQuery.

I have an index page which links to multiple pages and next to each page is a view count.

I would like the view count to refresh and automatically update every couple of seconds so that those on the page can view live updates of the page counts.

I've come accross the following script that works well based on a single Ajax element on the page, but what about 10 or more?

Is there a more efficient way (short of cutting and pasting the statement 10 times) to get all the fields to update individually?

<?php
// File: ajax.php
    // Ajax refresh hits
    if(isset($_GET['refresh'])){
        // Uses the get_page_views() function which takes an ID and retreives that page view count. The ID is passed by the AJAX script.
        if($_GET['refresh'] == 'hits') echo get_page_views($_GET['id']);
    };
?>

This si the code to the HTML page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax - PHP example</title>

<script language="javascript" type="text/javascript" src="jquery-1.3.2.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function(){
       //ajax.php is called every second to get view count from server
       var ajaxDelay = 1000;
       setInterval(function(){
      // Refresh details.
      $('#zone-111').load('ajax.php?refresh=hits&id=111');
      $(#zone-222').load('ajax.php?refresh=hits&id=222');
      $(#zone-333').load('ajax.php?refresh=hits&id=333');
      $(#zone-444').load('ajax.php?refresh=hits&id=444');
      $(#zone-555').load('ajax.php?refresh=hits&id=555');
     }, ajaxDelay);
    });
</script>

</head>

<body>

<div align="center" id="zone-111">--</div>
<br />
<div align="center" id="zone-222">--</div>
<br />
<div align="center" id="zone-333">--</div>
<br />
<div align="center" id="zone-444">--</div>
<br />
<div align="center" id="zone-555">--</div>
<br />

</body>
</html>

Any suggestion on how I can make this script/code more efficient would be greatly accepted.

Kind regards,

P.

+3  A: 

Send all of the ids at once as a JSON array. On the server side, build a JSON object containing key/value pairs of the ids/counts. Then iterate through the keys on the client when you get the result and set each count in turn in the related DIV.

$(document).ready(function(){
   //ajax.php is called every second to get view count from server
   var ajaxDelay = 1000;
   var ids = [];
   $('[id^="zone-"]').each( function() {
      ids.push( this.id );
   });
   setInterval(function(){
            $.ajax({
                url: 'ajax.php',
                dataType: 'json',
                type: 'get',
                data: { refresh: 'hits', ids: ids },
                success: function(data) {
                    for (var key in data) {
                        var div = $('#zone-' + key).html( data[key] );
                    }
                }
            });
    }, ajaxDelay);
});
tvanfosson
A: 

Thanks for the JSON suggestions, I wasn't quite sure how to implement it though and I've come up with this solution that works quite well so far. Feedback would be great.

    <script type="text/javascript" language="javascript">
     $(document).ready(function(){
        setInterval(function(){
       $('.views').each(function(){
        $(this).load('ajax.php?id='+this.id);
       });
      }, 5000);
     });  
    </script>

And in the HTML you just assign the class 'views' to the element that you want updated and the store the 'ID' as the id eg:

<p class="views" id="123"><!-- content appears here. --></p>
paperclip