Hi Guys!
I'm currently trying to refresh a DIV on my page that is linked to MYSQL (changes if database has 1 or more rows) without refreshing the entire page, I've tried using javascript although it didn't seem to work and so Im back to the drawing board, Im not very experienced with Jquery or Javascript to do it on my own, I only know PHP, CSS, HTML the easier ones :P

So I was hoping someone could shed some light on how I could possibly go about this... - I don't want to use Iframes either as the the div is a button which opens a hidden div on the page (parent page) so I don't think iframes would be best either

Any help would be great!
Thank you in advance :)

Dani AI

Generated

A simple, reliable pattern is to have a tiny server endpoint that returns a small state (boolean or count) and have the page poll that endpoint or use a push mechanism. and pointed the right way — the difference is in how you poll and what you update in the DOM. Because your DIV is also a clickable control, update a child element or a badge (text or data-attribute) instead of replacing the whole button/container so event handlers stay intact.

Example client-side polling (modern Fetch, avoids overlapping requests and includes basic backoff):

let stopped = false;

async function pollStatus(interval = 3000) {
  while (!stopped) {
    try {
      const res = await fetch('/status.php?ts=' + Date.now(), { cache: 'no-store' });
      if (!res.ok) throw new Error(res.status);
      const data = await res.json();
      // update only the small element inside the button, not the button itself
      document.getElementById('badge').textContent = data.exists ? '1' : '';
      await new Promise(r => setTimeout(r, interval));
    } catch (err) {
      console.error('poll error', err);
      await new Promise(r => setTimeout(r, interval * 2)); // simple backoff
    }
  }
}

window.addEventListener('beforeunload', () => { stopped = true; });
pollStatus();

Minimal server-side responder (PHP + PDO; return JSON, set no-cache):

<?php
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');
// use a read-only DB user and prepared queries
$pdo = new PDO('mysql:host=...;dbname=...', 'user', 'pass', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->query("SELECT EXISTS(SELECT 1 FROM your_table WHERE some_condition)");
$exists = (int)$stmt->fetchColumn();
echo json_encode(['exists' => $exists]);

Notes: use an appropriate poll interval to avoid DB load; prefer EXISTS or indexed queries for boolean checks (). For true server push, consider Server-Sent Events (MDN SSE). Ensure correct headers (see PHP header) and check the browser Network console when troubleshooting.

Recommended Answers

All 2 Replies

Hi, I would do it using JQuery.

I just didn't understood if the refresh will be trigerred by some user event or if it should refresh automatically.

function requestDivContent()
{
	var url = "http://myPage.com"; // URL to get the data
	var data = // Paramters, PHP Ex.: $name = $_POST["name"];
	{
		name : "name", 
		id : 20 
	};
	
	$.post(url, data, showDivContent); // Send the request
	
	// if you don't need to pass any data
	// $.post(url, showDivContent);
}

function showDivContent(divContent)
{
	$("#divContent").html(divContent); //Replace any existing content
}

// -------------------------------------------
// IF it should do automatically

var oTimer;

function initMySQLLink()
{
	var time = 5000; // 5 seconds
	oTimer = setInterval(requestDivContent, time); // Start the timer and save the it's reference
}

function stopMySQLLink()
{
	clearInterval(oTimer); // Cancel the timer
}

Links:
$.post()

It should work (I didn't test it), but there is no error handling. To handle errors you should use $.ajax()

Here is a condensed version:

var oTimer;

function refreshDivContent()
{
	oTimer = setInterval
	(
		function()
		{
			$.post
			(
				"http://myPage.com", 
				{name : "name", id : 20}, 
				function(divContent)
				{
					$("#divContent").html(divContent);
				}
			); 
		},
		5000
	);
}

Hope it helps.

You can do it using AJAX

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.