MikeS
MikeS

Reputation: 383

How can I turn data from MySQL to a jQuery variable?

New with jQuery. Here's what I have so far - basically, I want jQuery+ajax to get the most current date for a certain item. The script refreshes every 1 second.

This is the script:

<script>
var auto_refresh = setInterval(
function()
{
$.ajax({
    type: "POST",
    url: "gettime.php",
    data: ({i : <?=$itemid;?>}),
    function(data){
        var s = data;
    }
});
var t = s.split(/[- :]/); //split time from mysql
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>

And 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; //sample date is 2012-04-13 10:03:37
?>

Upvotes: 1

Views: 133

Answers (1)

bfavaretto
bfavaretto

Reputation: 71939

You have to do everything inside the ajax callback, because data and s are only available there (and when it runs):

var auto_refresh = setInterval(function(){
    $.ajax({
        type: "POST",
        url: "gettime.php",
        data: ({i : <?=$itemid;?>}),
        complete: function(data){
            var s = data;
            var t = s.split(/[- :]/); //split time from mysql
            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);

Upvotes: 3

Related Questions