0

Hello I have the following tasks:


  • Retrieve data from database and save to array (CHECK)
  • Send array from Controller to View (CHECK)
  • Pass that array to javascript function using json_encode (CHECK)
  • Plot array using Bootstrap Charts (PROBLEM!)

If I use the standard array that comes with Bootstrap chart (var d below) it works. However when I try to use my code nothing happens. Where am I failing?

var d = [[-373597200000, 315.71], [-370918800000, 317.45], [-368326800000, 317.50], [-363056400000, 315.86]]

I use instead the following line of code:

var d =  JSON.parse( '<?php echo json_encode($my_values) ?>' );

Here is and example of what my array looks like if I print it and the empty graph in the middle: http://postimg.org/image/3t3paj3vn/

Here is my full code :

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Flot Examples: Time Axes</title>
    <link href="../examples.css" rel="stylesheet" type="text/css">
    <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]-->
    <script language="javascript" type="text/javascript" src="../../jquery.js"></script>
    <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
    <script language="javascript" type="text/javascript" src="../../jquery.flot.time.js"></script>

</head>
<body>
            <select id="chapter_select">
                 <option value="0"> Select Patient</option>
                 <?php foreach($patients as $patient):?>
                        <option value= <?php echo $patient->id?> > <?php echo $patient->name ?>                            </option>
                <?php endforeach?> 
            </select><br><br>
                <?php $i= 0;?>
                <?php foreach($datas as $row):?>
                    <?php  $my_values[$i] = (array($row['data'],$row['total']));?>
                    <?php $i = $i+1;?>
                <?php endforeach;?>

    <div id="content">

        <div class="demo-container">
            <div id="placeholder" class="demo-placeholder"></div>
        </div>

        <p>Monthly mean atmospheric CO<sub>2</sub> in PPM at Mauna Loa, Hawaii (source: <a href="http://www.esrl.noaa.gov/gmd/ccgg/trends/">NOAA/ESRL</a>).</p>

        <p>If you tell Flot that an axis represents time, the data will be interpreted as timestamps and the ticks adjusted and formatted accordingly.</p>

        <p>Zoom to: <button id="whole">Whole period</button>
        <button id="nineties">1990-2000</button>
        <button id="latenineties">1996-2000</button></p>

        <p>Zoom to: <button id="ninetyninequarters">1999 by quarter</button>
        <button id="ninetynine">1999 by month</button>
        <button id="lastweekninetynine">Last week of 1999</button>
        <button id="lastdayninetynine">Dec. 31, 1999</button></p>

        <p>The timestamps must be specified as Javascript timestamps, as milliseconds since January 1, 1970 00:00. This is like Unix timestamps, but in milliseconds instead of seconds (remember to multiply with 1000!).</p>

        <p>As an extra caveat, the timestamps are interpreted according to UTC and, by default, displayed as such. You can set the axis "timezone" option to "browser" to display the timestamps in the user's timezone, or, if you use timezoneJS, you can specify a time zone.</p>

    </div>

    <div id="footer">
        Copyright &copy; 2007 - 2014 IOLA and Ole Laursen
    </div>


    <script type="text/javascript">

    $(function() {

    var d =  JSON.parse( '<?php echo json_encode($my_values) ?>' );

        $("#latenineties").click(function () {
            $.plot("#placeholder", [d], {
                xaxis: {
                    mode: "time",
                    minTickSize: [1, "year"],
                    min: (new Date(1996, 0, 1)).getTime(),
                    max: (new Date(2000, 0, 1)).getTime()
                }
            });
        });

        $("#ninetyninequarters").click(function () {
            $.plot("#placeholder", [d], {
                xaxis: {
                    mode: "time",
                    minTickSize: [1, "quarter"],
                    min: (new Date(1999, 0, 1)).getTime(),
                    max: (new Date(2000, 0, 1)).getTime()
                }
            });
        });

        $("#ninetynine").click(function () {
            $.plot("#placeholder", [d], {
                xaxis: {
                    mode: "time",
                    minTickSize: [1, "month"],
                    min: (new Date(1999, 0, 1)).getTime(),
                    max: (new Date(2000, 0, 1)).getTime()
                }
            });
        });

        $("#lastweekninetynine").click(function () {
            $.plot("#placeholder", [d], {
                xaxis: {
                    mode: "time",
                    minTickSize: [1, "day"],
                    min: (new Date(1999, 11, 25)).getTime(),
                    max: (new Date(2000, 0, 1)).getTime(),
                    timeformat: "%a"
                }
            });
        });

        $("#lastdayninetynine").click(function () {
            $.plot("#placeholder", [d], {
                xaxis: {
                    mode: "time",
                    minTickSize: [1, "hour"],
                    min: (new Date(1999, 11, 31)).getTime(),
                    max: (new Date(2000, 0, 1)).getTime(),
                    twelveHourClock: true
                }
            });
        });

        // Add the Flot version string to the footer

        $("#footer").prepend("Flot " + $.plot.version + " &ndash; ");
    });

    </script>

</body>
</html>
2
  • You don't need the json.parse at all. var d = <?php echo json_encode(...); ?>; is all that's necessary. remember that JSON IS javascript. once php spits out the encoded json into the page, the browser will only see var d = [valid javascript data here] Commented Apr 24, 2015 at 14:41
  • I've used json.parse because json_enconde was not working... The effect was the same. But still no graph. Commented Apr 24, 2015 at 14:49

2 Answers 2

1

The problem was that the bootstrap code did not recognize my datetime. So, I converted it to UNIX Timestamp. Here is my query

$query = $this->db->query("	SELECT exam.id AS exam, UNIX_TIMESTAMP(exam.date) AS data, SUM( choice.value ) AS total
									FROM exam INNER JOIN choice ON exam.id = choice.exam_id
									WHERE exam.patient_id =  $patient_id AND exam.id = choice.exam_id GROUP BY exam.date");
		$data = array();
		foreach ($query->result() as $row)
		{
			$data[] = array(
        'exam' => $row->exam,
		'data' => $row->data,
        'total'  => $row->total
		);
}
		return $data;

And then used Faran Ali suggestion
var d =

	
var d = '<?php json_encode($my_values); ?>

Sign up to request clarification or add additional context in comments.

1 Comment

forget echo var d = '<?php json_encode($my_values); ?>
0

Try this:

var d =  JSON.parse( '<?php echo($my_values); ?>' );

6 Comments

Why should the OP "try this"? Please add an explanation of what you did and why you did it that way not only for the OP but for future visitors to SO.
Same result Faran... Able to print the values but nothing shows in the graph.
var d = '<?php json_encode($my_values); ?>'; will work, js GRAPHs works with JSON. JSON.PARSE convert json into array that's why it was not working @DMBorges
@DMBorges check this example you will understand JSON.parse var text = '{"employees":[' + '{"firstName":"John","lastName":"Doe" },' + '{"firstName":"Anna","lastName":"Smith" },' + '{"firstName":"Peter","lastName":"Jones" }]}'; obj = JSON.parse(text); console.log(obj);
I found the problem! It works with var d = '<?php json_encode($my_values); ?>' however the problem is with the line from the bootstrap code. xaxis: { mode: "time", I need to print day-mon (14-Mar) however this mode does not work with datetime...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.