Reputation: 1
jquery noob here.
I have a question for pros and people with jquery experience. I created this script, but I'm struggling with making it more efficient. Anyway, the idea is that I have multiple entries on HTML page that come from MYSQL database via PHP.
So,
A - A2
B - B2
C - C2
No, A,B and C are static. It's just being read from the database. And A2,B2,C2 are dynamic elements that are updated every 10 seconds. In the current form I have multiple copies of javascript for each entry, which is extremely inefficient. At around 100 entries, my CPU spikes to 20-40% usage.
The script is below:
<script>
$(function() {
var refreshId = setInterval(function()
{
$('#UpdateDiv<?php echo $entry; ?>').load('live.php?entry=<?php echo $entry; ?>').fadeIn("slow");
}, 10000);
});
</script>
<?PHP
echo '<div id="UpdateDiv'.$entry.'"></div>';
?>
Thank you!
Upvotes: 0
Views: 1446
Reputation: 29
Your problem is making the requests individually. By combining all requests into one request every ten seconds or so, you'll greatly increase your page's efficiency.
Your javascript to request and display all entries at once:
var get_entries = function () {
$.ajax({
post: true,
url: "entries.php",
data: {
entries: [1, 2, 3, 4, 5, 6, 7, 8]
},
success: function (response) {
var entry_updates = JSON.parse(response);
for (var entry in entry_updates) {
$("#UpdateDiv" + entry).html(entry_updates[ entry ]);
}
}
});
};
setInterval(get_entries, 10000);
And your PHP to handle all entries at once:
<?php
$entry_updates = array();
if (isset($_POST['entries'])) {
foreach ($_POST['entries'] as $entry) {
$entry_updates[ $entry ] = func_get_entry_info($entry);
}
}
echo json_encode($entry_updates);
Upvotes: 0
Reputation: 12335
The problem is that each div element has its own script, and therefore sends its own request.
Basically, every 10 seconds, you are making 100 requests.
Instead you should have a single script loading the new data every 10 seconds (perhaps in json format), which then changes each div's content.
You can do that by iterating over each element in a json array, and setting (pseudocode)
for each i
div[i].innerHTML(jsonarray[i])
where div[i] is the jquery object representing each div.
To load the data for every entry, you will need to create a new page using php page named (for example)
live.json
which puts each div content into a json array ["content1","content2"]
If the name of the php page does not have a .json suffix, you will need the ajax call (you can use the ajax jquery function - http://api.jquery.com/jQuery.ajax/) to have a setting to interpret it as a .json file.
Then set up a callback for when the response is successful, and use that for loop to put content in each div element.
Upvotes: 1