MikeS
MikeS

Reputation: 383

How can I make an ajax call using jQuery every second?

Okay, so I managed to get everything running - one last thing. Basically, one jQuery+ajax function adds 15 seconds to the date and adds a new row to MySQL. I need to put in a new row so I can get the last 5 rows for the history:

<?php 
include("inc/dblink.inc");
$itemid = intval($_POST['i']);
$bid = intval($_POST['b']);
$row = mysql_fetch_array(mysql_query("SELECT * FROM test WHERE itemid=$itemid ORDER BY bidid DESC LIMIT 0,1"));
$date = $row['date'];
$newdate = strtotime($date);
$newerdate = ($newdate + 15);
$newestdate = date("Y-m-d H:i:s", $newerdate);
mysql_query("INSERT INTO test (date,bid,itemid) VALUES ('$newestdate','$bid','$itemid')");
?>

The second script refreshes every second and displays the data from the table.

<script type="text/javascript">
var auto_refresh = setInterval(
function()
{
$('#timeleft').load('gettime.php', { i: <?=$itemid;?> }).show();
$.ajax({
    type: "POST",
    url: "gettime.php",
    data: ({i : <?=$itemid;?>}),
    success: function(data){
        var s = data;
        var t = s.split(/[- :]/);
        var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
        $('#defaultCountdown').countdown({until: d,compact: true, 
        description: ''});
    }
});
}, 1000);
</script>

Here's gettime.php

<?php 
include("inc/dblink.inc");
$itemid = intval($_POST['i']);
$row = mysql_fetch_array(mysql_query("SELECT * FROM test WHERE itemid='$itemid' ORDER BY bidid DESC LIMIT 0,1"));
$date = $row['date'];
echo $date;
?>

And I also used Keith Wood's jQuery countdown script found in http://keith-wood.name/js/jquery.countdown.js

The problem:

This line $('#timeleft').load('gettime.php', { i: <?=$itemid;?> }).show(); is good. The new time with 15 seconds added shows up without a problem. It's the countdown I'm having issues with. It doesn't add 15 seconds to the timer but if I refresh the whole page, I can see that 15 seconds was added.

What am I doing wrong? Fairly new with jQuery. Thanks!

You can see it in action here.

Upvotes: 1

Views: 1116

Answers (4)

Coscho
Coscho

Reputation: 89

Add this in ajax:

$('#defaultCountdown').countdown('option', {
    format: 'DHMS', until : d
});

Works for me.

Upvotes: 1

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

There's a couple of major issues here, and some minor ones.

Date Format

It's much simpler to work with a unix timestamp rather than a formatted date. PHP and javascript are very similar in this regard. Both are based on the same "epoch", 00:00 1 Jan 1970. UNIX/PHP work in seconds from that date and javascript works in milliseconds. Therefore a javascript Date object can be initialized with new Date(unix_timestamp * 1000); without the need for tricky string handling.

Countdown

Countdown is designed to free-run down to zero with a resolution of 1 second (then fire an optional callback function). With a poll interval of 1 second, it's not necessary to reinitialize the countdown timer every time - only when the returned timestamp has changed.

Efficiency

With setinterval, it is kinder to client processors to create as many objects/strings as possible once outside the setinterval function. This particularly applies to jQuery statements with (static) selectors, as these cause the (potentially large) DOM to be searched.

Putting all that together, my javascript would look like this:

$(function(){
    var $$ = {//cached jQuery objects
        timeleft: $('#timeleft'),
        defaultCountdown: $('#defaultCountdown')
    };
    var map_1 = {//namespace for setInterval and countdown data
        url: 'gettime.php',
        lastTimeStamp: 0,
        countdown_settings: {until:null, compact:true, description:''},
        itemid: <?=$itemid;?>
    };
    var auto_refresh = setInterval(function() {
        $$.timeleft.load(map_1.url, {i:map_1.itemid}).show();
        $.ajax({
            type: "POST",
            url: map_1.url,
            data: {i:map_1.itemid},
            success: function(unixTimeStamp) {
                unixTimeStamp = parseInt(unixTimeStamp);
                if(unixTimeStamp !== map_1.lastTimeStamp) {
                    map_1.countdown_settings.until = new Date(parseInt(unixTimeStamp) * 1000);
                    $$.defaultCountdown.countdown(map_1.countdown_settings);
                    map_1.lastTimeStamp = unixTimeStamp;
                }
            }
        });
    }, 1000);
});

Of course, to make this work, the PHP statement echo $date; will need to be modified to echo the unix timestamp representation of the date. That should be fairly trivial with knowledge of the date format as stored in the db.

Edit: Unix epoch is 00:00 (midnight) 1 Jan 1970, not 12:00 (midday), doh! Javascript is the same so no negative affect on the code.

Upvotes: 3

Satish
Satish

Reputation: 6485

I think your php script variable in this line is generate only once, that is why, it works only once (that is every page refresh).

 $('#timeleft').load('gettime.php', { i: <?=$itemid;?> }).show();

update your JS success code to update the variable, so the page is updated for every call.

Upvotes: 1

Gaurav Sharma
Gaurav Sharma

Reputation: 4052

Your date object i.e. 'd' is initialized only once i.e. the first time the page loads. Find a way to re-initialize it every time you run the countdown function.

Upvotes: 2

Related Questions