Reputation: 2194
My site currently has to load 6 different PHP pages to fill info for 7 DIV's.
Some refresh every 5 seconds, some every second.
I would rather load the one single PHP page every second, and split the details to all of the DIV's. That way only 1 request is sent per second, rather than 3 or 4 requests.
so --> api/getdata.php will echo: "$5.93, $10.36, 27:31 1, 22, Joe". Then JQuery will need to split each comma to a different DIV. Something like this:
setInterval(function() {$('#balance, #pot, #timer, #round, #id, #username').load('api/getdata.php');}, 1000);
I had a look on Google, but couldn't find anything to what I am looking for.
My current method (very bad) is:
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
$('#GetBalance, #GetBalanceWithdraw').load('get/GetBalance.php');
$('#Clock').load('get/Clock.php');
$('#GetPot').load('get/GetPot.php');
setTimeout(function() {$('#errmsg').fadeOut('slow');}, 5000);
setInterval(function() {
$('#GetPot').load('get/GetPot.php');
$('#TotalBids').load('get/TotalBids.php');
}, 2500);
setInterval(function() {$('#GetBalance, #GetBalanceWithdraw').load('get/Balance.php');}, 5000);
setInterval(function() {$('#GetBalance').load('get/Balance.php');}, 5000);
setInterval(function() {$('#Clock').load('get/Clock.php');}, 1000);
});
</script>
Upvotes: 0
Views: 818
Reputation: 27765
So you will need to split your response and only then assign to elements. At this moment you add same value to all elements.
You need something like this:
setInterval(function() {
$.get( 'api/getdata.php', function( data ) {
var result = data.split( ', ' );
$( '#balance' ).text( result[ 0 ] );
$( '#pot' ).text( result[ 1 ] );
$( '#timer' ).text( result[ 2 ] );
$( '#round' ).text( result[ 3 ] );
$( '#id' ).text( result[ 4 ] );
$( '#username' ).text( result[ 5 ] );
} );
}, 1000);
But in this case you can flood you server with requests if back-end will slow with response, so better to call new AJAX after 1 second after previous loaded using recursive function:
function updateData() {
$.get( 'api/getdata.php', function( data ) {
var result = data.split( ', ' );
$( '#balance' ).text( result[ 0 ] );
$( '#pot' ).text( result[ 1 ] );
$( '#timer' ).text( result[ 2 ] );
$( '#round' ).text( result[ 3 ] );
$( '#id' ).text( result[ 4 ] );
$( '#username' ).text( result[ 5 ] );
setTimeout( updateData, 1000);
} );
}
updateData();
Upvotes: 1
Reputation: 128
If you have all your strings in one string and comma separated, you could do this:
$( "#result" ).load( "ajax/test.html", function(data) {
spread_the_news(data);
});
and then
function spread_the_news(data)
{
var res = data.split(",");
update_div_0_with_data(res[0]);
update_div_1_with_data(res[1]);
...
}
Upvotes: 0