I have written a plugin for WordPress which generates a jQuery.accordion list of content that it pulls from a database. I also have it pulling newer results from the database every 5 seconds via a separate page (update.php) through the jQuery.load method.
The problem I’m encountering is that I’m generating the full HTML for the div in the update.php file. It seems like I could just make it query the database and then return the results to the main file, but I’m not sure how to go about doing that. Basically, my concern here is efficiency, because with the way I’m doing things it may be considerably taxing on browser resources. I have a hunch that memory usage will continue to climb with this method until it inevitably peaks and the browser crashes.
I’m looking for any guidance on how to better code this. I’ve provided proof-of-concept examples below, so I’d love for anyone to offer feedback, whether constructive or critical. Thank you!
main.php:
<script type="text/javascript">
$(function() {
$("#accordion").load("update.php");
var refresh = setInterval(function() {
$k("#accordion").load("update.php");
}, 5000);
});
</script>
<div id="accordion"></div>
update.php:
<?php
function page_update() {
global $wpdb;
$out = '';
$out .= '<script type="text/javascript" src="jquery-1.5.min.js"></script>';
$out .= '<script type="text/javascript" src="jquery-ui-1.8.11.custom.min.js"></script>';
$out .= '<script type="text/javascript">
var $j = jQuery.noConflict();
$j(function() {
$j("#accordion").accordion();
});
</script>';
$sql = "SELECT * FROM table ORDER BY name DESC;";
$results = $wpdb->get_results($sql);
foreach($results as $res) {
$out .= '<h3>'.$res->name.'</h3>';
$out .= '<div id="content-'.$res->name.'">'.$res->score.'</div>';
}
echo $out;
}
page_update();
?>
You should not use the global keyword. Why?
Before you redraw all your accordion div, you should make a function that check if there is any changes in the database. If there is no changes, their is no need to redraw.
If there is a change, you could redraw only the affected row.