I have found a fairly generic script for refreshing the content of a div without refreshing the whole page and although it works fine, there are a few things I would like to improve on if they are possible.

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
 $(document).ready(function() {
 	 $("#refreshdiv").load("activity.php");
   var refreshId = setInterval(function() {
      $("#refreshdiv").load('activity.php?randval='+ Math.random());
   }, 9000);
   $.ajaxSetup({ cache: false });
});
</script>
<div id="refreshdiv">
</div>

There are, in all, 6 divs that I am looking to refresh. 3 of them show on every page and the other 3 are all on the same page (giving a total of 6 on that page) and my 2 questions are.......

1. All of the divs are pulling results from a MySQL db, via Php, and what I have had to do for now is set up a new page for each of the divs content and have them pulled into the requesting page, resulting in 6 new pages.
The main problem with this is that each refresh on each div is counting as a page impression on the hosting company's analytics, meaning we are not getting a true set of page view results.
Is there a way that I can keep the content all on the one page and have Ajax refresh the query/result within the div tags instead of loading/reloading an external page.
I assume that the '.load' section may be the key to this. My guess is that it would be possible to write a function that would do this but am not sure where to start.

2. At the moment, there are 6 different scripts to allow the refresh of 6 different divs. Is there a way to cover all 6 divs in one script? I would assume that I could name all the divs the same but if question 1 is not achievable, then I will still have to call 6 different pages within the script. I would imagine that I could wrap the whole page in a refreshing div but would guess that is not recommended.


Thanks in advance for any help.
Steve

Dani AI

Generated

Short answer: yes — you don't need six separate PHP pages. Serve small, fragment-only responses from a single AJAX endpoint (or from the same page when passed an ajax flag) and poll those endpoints. That prevents the host's page-impression bookkeeping from firing (because you won't be requesting a full page with the site's analytics code), and it makes one client script able to refresh multiple divs. , your Google Analytics filter is a practical quick fix; the fragment-endpoint approach is cleaner and scales better.

Server-side pattern (keep it tiny, whitelist widgets, use prepared statements and escape output):

// ajax.php
$allowed = ['score','timeline','lineup','players','stats','news'];
$widget = $_GET['widget'] ?? '';
if (!in_array($widget, $allowed)) { http_response_code(400); exit; }
// connect with PDO and prepared statements
header('Content-Type: text/html; charset=utf-8');
// output only the HTML fragment for this widget (no header/footer, no analytics)
echo getWidgetHtml($widget);

Client-side: one polling loop that updates multiple divs and pauses when the tab is hidden (cuts server load):

const widgets = ['score','timeline','lineup','players','stats','news'];
let timer;
function poll(){
  widgets.forEach(id=>{
    const el = document.getElementById(id); if(!el) return;
    fetch('/ajax.php?widget='+encodeURIComponent(id))
      .then(r=>{ if(!r.ok) throw new Error(r.status); return r.text(); })
      .then(html=> el.innerHTML = html)
      .catch(e=> console.error('poll', id, e));
  });
}
function start(){ poll(); timer = setInterval(poll, 9000); }
function stop(){ clearInterval(timer); }
document.addEventListener('visibilitychange', ()=> document.hidden ? stop() : start());
start();

Extra tips: whitelist widget names to avoid abuse, cache query results (memcached/Redis or simple file cache) to reduce DB hits, return JSON when possible and render on the client to save bandwidth, and consider Server-Sent Events or WebSockets for true real‑time match updates instead of frequent polling. : host analytics often count raw HTTP requests or full-page hits — returning fragments without the tracking snippet prevents that. : include can be reused inside the single endpoint to share code, but ensure those includes don't inject the page template or analytics.

Recommended Answers

All 3 Replies

A couple questions... How does the hosting company analytic counts a page visit? Does it count via HTTP request or else? Do you have an authority to change the rule of visited page counter?

what if there's a php link include?

Firstly, apologies for not responding to the original reply. I had to reformat my PC and had completely forgotten about this thread until I just got an email notification.

I actually got around the problem I had by setting Google Analytics for the site in question so only the pages I want tracked are being tracked.

However, I would still like to know if there is a way of updating a query via Ajax. The site is for a football(soccer) team and a future plan is to have live updates during a game. Something similar is already done via twitter but they would like to move everything into the site code itself.

Obviously it can be done, once again, via having the query in an internal page pulled into a div but am curious if there is a way to do it without external pages?

Thanks
Steve

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.