PDA

View Full Version : Resolved setInterval initial value



nicksalad
10-27-2009, 06:37 PM
Hello,

I have the next script to get some info from the database, it refreshes itself every 5 seconds, but, every time I reload the page I have to wait 5 secs just for it to show, I know i can go to #online for example and place there the initial value, but I would like to do it with javascript, seems more clean.


<script type="text/javascript">
$(function() {

setInterval(function() {
$.getJSON('include/ajaxStats.php', function (data) {
$('#online').html(data.online);
$('#accts').html(data.accts);
$('#chars').html(data.chars);
});
}, 5000);

});
</script>

Also if this code can be improved don't doubt on let me know, I'm just a newbie.

Thanks much!

jscheuer1
10-27-2009, 06:47 PM
I'm not clear on where data is coming from, unless it is from $.getJSON itself. But if it works as an interval, it should work as a function, so try:


$(function() {
function myFunc() {
$.getJSON('include/ajaxStats.php', function (data) {
$('#online').html(data.online);
$('#accts').html(data.accts);
$('#chars').html(data.chars);
});
}
myFunc();
setInterval(myFunc, 5000);

});

I'm assuming this is jQuery here and that the wrapper is the shorthand form of the document.ready function.

nicksalad
10-28-2009, 01:12 AM
I'm not clear on where data is coming from, unless it is from $.getJSON itself. But if it works as an interval, it should work as a function, so try:


$(function() {
function myFunc() {
$.getJSON('include/ajaxStats.php', function (data) {
$('#online').html(data.online);
$('#accts').html(data.accts);
$('#chars').html(data.chars);
});
}
myFunc();
setInterval(myFunc, 5000);

});

I'm assuming this is jQuery here and that the wrapper is the shorthand form of the document.ready function.

Yes it is jQuery, sorry for not mention it, and on the php side looks like this:


<?php

require_once('config.php');
require_once('stats.php');

$accts = accounts_total();
$chars = chars_total();
$on = online_total();
$lim = $GLOBALS['cfg']['maxvirtualonline'];

echo '{online: '.$on.', accts: '.$accts.', chars: '.$chars.'}';

?>

Can it be improved? It works.. but dunno if is good hehe.

Regarding your post, it works like a charm, thanks again! you are a life savior. :)

jscheuer1
10-28-2009, 07:20 AM
Looks pretty straightforward to me, but I'm no expert at PHP.

Incidentally, on the javascript side, you my alternatively use/return the arguments.callee property of a self executing anonymous function if you like:


<script type="text/javascript">
$(function() {

setInterval((function() {
$.getJSON('include/ajaxStats.php', function (data) {
$('#online').html(data.online);
$('#accts').html(data.accts);
$('#chars').html(data.chars);
});
return arguments.callee;
})(), 5000);

});
</script>

Which may appeal to the jQuery mindset more than my first solution does. Though I believe the first solution is a slight bit more efficient.