I have a PHP code which grabs data from site and it should be updated every second, I don't want to refresh whole page, I just want to refresh the data.
please suggest something.

Dani AI

Generated

A short, practical plan that builds on and : use AJAX to update only the part of the page that shows the changing data, but avoid blindly polling your PHP endpoint every second if that PHP script re-scrapes a remote site on each request. If the remote fetch is expensive, do the fetch once on the server (or cache it for a few seconds) and let clients request the cached value frequently.

A robust client pattern (prevents overlapping requests) and a minimal server approach:

// client.js
let controller;
function poll() {
  if (controller) controller.abort();
  controller = new AbortController();
  fetch('/data.php', { signal: controller.signal })
    .then(r => r.json())
    .then(data => {
      document.getElementById('myValue').textContent = data.value;
      setTimeout(poll, 1000); // next poll
    })
    .catch(err => {
      console.error('poll error', err);
      setTimeout(poll, 2000);
    });
}
poll();
<?php
// data.php - return small JSON, cache external fetch to avoid hammering remote site
header('Content-Type: application/json; charset=utf-8');
$cache = '/tmp/data.json';
if (file_exists($cache) && time() - filemtime($cache) < 5) {
  echo file_get_contents($cache);
  exit;
}
// perform external fetch once, parse, store minimal JSON
$data = ['value' => '...']; // replace with actual fetch/parsing
file_put_contents($cache, json_encode($data));
echo json_encode($data);

If many clients or true real-time is needed, prefer server push (SSE or WebSockets) instead of 1s polling. Troubleshooting tips: watch the Network tab to confirm request timing and payload size, ensure proper Content-Type and caching headers, and add exponential backoff on errors.

Recommended Answers

All 2 Replies

You can use AJAX. Have a look for some tutorials. Also you can get some more information in the AJAX-Forum on Daniweb.
Regards

Member Avatar for Member #120589

You could use ajax for this, but that's a lot of calls on the server. What are you trying to do? Could you do one call to the server and then let just JS do something every second?

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.