weixin_33709364 2017-04-12 07:12 采纳率: 0%
浏览 54

chart.js php实时更新

Using Chart.JS (http://www.chartjs.org/docs/), I want to show live update results from database in page. Can someone show me an example with AJAX how to get results and pass them in this code?

PHP:

$query2 = "SELECT * FROM CMS_Stats ";
$result2 = $conn->query($query2);

while($row2 = $result2->fetch_assoc()) {
   $members[] = $row2['MembersOnline'];
   $guests[] = $row2['GuestsOnline'];
}

JS:

var canvas = document.getElementById('myChart');
var data = {
    labels: ['Now'],
    datasets: [
        {
            label: "Members online",
            lineTension: 0.3,
            backgroundColor: "rgba(75,192,192,.90)",
            borderColor: "rgba(75,192,192,1)",
            pointRadius: 3,
            pointHitRadius: 10,
            data: <?php echo json_encode($members) ?>,
        },
        {
            label: "Guests online",
            lineTension: 0.3,
            data: <?php echo json_encode($guests) ?>,
            backgroundColor: "rgba(255, 185, 84,.90)",
            pointBorderColor: "rgba(211,84,0 ,1)",
            pointBackgroundColor: "#fff",
            pointRadius: 3,
            pointHoverBackgroundColor: "rgba(211,84,0 ,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)"
        }
    ]
};

var option = {
    showLines: true
};
var myLineChart = Chart.Line(canvas,{
    data:data,
  options:option
});
  • 写回答

1条回答 默认 最新

  • weixin_33725272 2017-04-12 07:22
    关注

    You'll need AJAX to run using interval:

    setInterval(ajaxFunction(), 5000); // 5 sec
    

    And in that function you have to call AJAX

    function showHint(str) {
    
    if (str.length == 0) { // case that doesn't call AJAX (can be discluded)
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {  // case that calls AJAX
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) { //successfully getting answer
                document.getElementById("txtHint").innerHTML = this.responseText; // this.responseText is answer you get
            }
        };
        xmlhttp.open("GET", "gethint.php?q=" + str, true); // your php file that works with recieved data and echoes answer
        xmlhttp.send();
    }
    
    }
    

    AJAX part is just a random fragment from w3schools, if you are new to AJAX then just search for AJAX PHP

    评论

报告相同问题?