0

I have a .php page that renders out a line plot Flot chart by querying my database. I would love some assistance in creating some ajax (or otherwise) code to dynamically update it every 60 seconds. Below is what I have. Thanks in advance:)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<style type="text/css">
body { font-family: Verdana, Arial, sans-serif; font-size: 12px; }
#placeholder { width: 450px; height: 200px; }
</style>

<!--[if lte IE 8]><script type="text/javascript" language="javascript" src="excanvas.min.js"></script><![endif]-->
<script type="text/javascript" language="javascript" src="flot/jquery.js"></script>
<script type="text/javascript" language="javascript" src="flot/jquery.flot.js"></script>

<?php

    $server = "myserver:1234";
    $user="dbuser";
    $password="userpass";  
    $database = "dbname";

    $connection = mysql_connect($server,$user,$password);
    $db = mysql_select_db($database,$connection);

    $query = "SELECT X, Y FROM listener_incr";
    $result = mysql_query($query);        

    $i = -60;

    while($row = mysql_fetch_assoc($result))
    {
        $dataset1[] = array($i,$row['Y']);
        $i++;
    }
    $final = json_encode($dataset1,JSON_NUMERIC_CHECK);
?>  

<script type="text/javascript">

var d1 = <?php echo $final; ?>;

$(document).ready(function () {
    $.plot($("#placeholder"), [
    { 
    label: "Number of items", data: d1, color: "#FB0026"}
    ], {
    xaxis: { show: true, axisLabel: "1hr", ticks: 6 },
    yaxis: { show: true, axisLabel: "", ticks: 12, min: 0, tickDecimals: 0, position: 1 }
    }
    );

});
</script>
</head>

<body>
    <div id="placeholder"></div>
</body>
</html>

Here is an example but it uses random number generation instead of a database dip.

square_eyes
  • 1,269
  • 3
  • 22
  • 52

1 Answers1

2

There are two ways you can do that

SOLUTION 1

*1.*If you want to dynamically refresh only the chart part of your page then do the following,

1.1.create a php page (e.g. chart-data.php) which fetches data from db and returns json as you have coded.

just to make it clear as seen in your code

<?php
    /*the code here has not been modified, it is used 
          as found from your example*/
    $server = "myserver:1234";
    $user="dbuser";
    $password="userpass";  
    $database = "dbname";

    $connection = mysql_connect($server,$user,$password);
    $db = mysql_select_db($database,$connection);

    $query = "SELECT X, Y FROM listener_incr";
    $result = mysql_query($query);        

    $i = -60;

    while($row = mysql_fetch_assoc($result))
    {
        $dataset1[] = array($i,$row['Y']);
        $i++;
    }
    $final = json_encode($dataset1,JSON_NUMERIC_CHECK);
echo $final;
?>  

1.2.add in your js code an ajax request,

/*it is not necessary to create a new document ready function, you can use the document ready function you already have in your example. Just place the setInterval code at the bottom of your document ready function*/

$(document).ready(function () {      

setInterval(function(){
        $.ajax({
            dataType:'json',  /*to avoid calling JSON.parse(data) in your callback function*/
            url: '/chart-data.php',
            success: function (data) {
console.log(data);//as mentioned in comments
                //1.either call plot again 
/*calling plot as seen in your code - start*/
                var d1 = data;/* JSON.parse(data) */
                $.plot($("#placeholder"), [{
                    label: "Number of items",
                    data: d1,
                    color: "#FB0026"
                }], {
                    xaxis: {
                        show: true,
                        axisLabel: "1hr",
                        ticks: 6
                    },
                    yaxis: {
                        show: true,
                        axisLabel: "",
                        ticks: 12,
                        min: 0,
                        tickDecimals: 0,
                        position: 1
                    }
                });
/*calling plot as seen in your code - end*/

                /*      
                //2. or just redraw, as found in http://stackoverflow.com/questions/6024474/refresh-reload-flot-in-javascript

    var newData = [[0,2],[1,3],[2,5]];

    plot.setData(newData);
    plot.setupGrid(); //only necessary if your new data will change the axes or grid
    plot.draw();
    */
            }//ajax props
        });//ajax
      },60000);//interval
    });//document ready

SOLUTION 2

*2.*If you are populating the js data from php while rendering the page, as you have already coded, you need to refresh your page every 60s from js or php with something like,

JS

setInterval(function(){
   window.location.reload(true);
    },60000);

or

PHP

<meta http-equiv="refresh" content="60" >
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
melc
  • 11,523
  • 3
  • 36
  • 41
  • Thanks I just want the chart to update so I'll try moving the php out of the page like in your first example. Thanks for the help! I'll get back as soon as I can. – square_eyes Oct 21 '13 at 09:27
  • I'm a little confused with all the examples and the formatting of your answer. I think I want to use the redraw example. New data may change my y axis, but not my x. – square_eyes Oct 21 '13 at 09:35
  • @square_eyes the formatting was messed up at some point of editing and possibly made a syntax error. I think now it is ok. It should work whether you call plot again or draw. In one of my apps i'm calling plot every time to refresh just the chart. – melc Oct 21 '13 at 09:46
  • I'm nearly there, I can see the chart-data.php being polled in the inspector. But the chart isn't being updated after the initial page load. I'm calling `var d1 = ;` now before the document ready function is that correct? – square_eyes Oct 21 '13 at 10:12
  • @square_eyes yes that is fine and since your chart gets drawn the first time that proves it. You may need to make the 60000 interval to 1000 in order to make testing easier/faster.Add a log line to make sure that ajax is called and retrieves data, do success: function (data) {console.log(data); and look at the console of the inspector. – melc Oct 21 '13 at 10:17
  • @square_eyes also check the path of the url i assumed it placed under the root context you may need to try url: 'chart-data.php' if it is in the same folder as your first php page. – melc Oct 21 '13 at 10:21
  • I changed `/chart-data.php` to `chart-data.php` now the update is parsed to the chart. Unfortunately the chart data series disappears. View page source shows the data is there so there, so something during the update breaks the Flot. I have a test example up if you are free to chat quickly. – square_eyes Oct 21 '13 at 10:28
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/39637/discussion-between-melc-and-square-eyes) – melc Oct 21 '13 at 10:33
  • Thanks for the detailed help. Very happy with this. – square_eyes Oct 21 '13 at 10:50