user1928362 user1928362 - 1 month ago 23
Ajax Question

jQuery .load returning empty div (PHP page)

I have a PHP control panel I'm currently working on. I need a div in one of my PHP files to automatically refresh and I came across an jQuery solution which can automatically reload certain parts of a website. The problem is every time I include the script, when the setInterval runs it just turns the div into a blank element instead of loading the content.

My site works by having a master PHP called "panel.php" which loads various HTML documents (.php files) using "include". One of those HTML documents is called "printers.php".

Inside printers.php I want to reload this div:

<div id="tsd"><?php echo time(); ?></div>


So at the top of my code in the head tag of "printers.php" I added this code:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
setInterval(function () {
$( "#tsd" ).load("panel.php #tsd");
}, 2000);
</script>


Now when the panel.php document loads, the timestamp shows for 2 seconds, then disappears and the div element just goes blank with no data in it. I can't figure out why it is reloading a blank div? Any ideas would help.

Answer

You forgot to add the GET parameters. Change your Interval script from:

$( "#tsd" ).load("panel.php #tsd");

to

$('#tsd').load('panel.php?page=printers #tsd');

Upon inspection of your panel.php code, I noticed this if statement:

if (!isset($_GET['page'])) 
    header('location: panel.php?page=dashboard');
else 
    include('restricted/sitepages/'.$_GET['page'].'.php');

Thereby, because you were omitting the GET parameter page it was loading the Dashboard page instead of the Printers page; and I'm guessing the Dashboard page does not have a div with the id tsd. Therefore it was loading nothing because #tsd does not exist in the loaded response.