i'm trying to make line chart in laravel using google chart and get data from database mysql.
Question:
how can i passing variable $bmi and $visits in data.addRows? so that i can showing the data using line chart.
here my code (php):
public function graphBmi($childName){
$name = DB::table('tm_child')->select('Child_Name')->distinct()
->where('Child_ID', 'LIKE', '%' . $childName . '%')->first();
$visit = DB::table('tm_Child')
->join('tr_visit', 'tm_child.Child_ID', '=', 'tr_visit.Child_ID')
->where('tr_visit.Child_ID', 'LIKE', '%' . $childName . '%')
->select('Visit_Date', 'tr_visit.Child_ID', 'Bmi_anak')
->distinct()->get();
if (!is_null($visit)) {
$visits = [];
$bmi = [];
$data[0] = array('day','counts');
foreach ($visit as $tgl) {
array_push($visits, $tgl->Visit_Date);
array_push($bmi, $tgl->Bmi_anak);
}
}
// return $visit;
echo json_encode($bmi); //number
echo json_encode($visits); //date visit
return View::make('ProfilAnak.BmiAnak.seeBmi')->with('visits',$visits)->with('bmi',$bmi);
}
here script for showing the chart
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
<script>
google.load('visualization', '1', {packages: ['corechart', 'line']});
google.setOnLoadCallback(drawBackgroundColor);
function drawBackgroundColor() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Visit');
data.addColumn('number', 'X');
data.addRows([
[new Date{{$visits}},{{$bmi}}]
]);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Popularity'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Related
I've been trying to work out why google charts won't plot this JSON data in a line chart
I've scoured the internet but can't find the answer, so calling on the big guns now ...
From a .CSV file loaded into a PHP array
Array
(
[0] => Array
(
[Time] => 16:37:36
[Value] => 27.1
)
[1] => Array
(
[Time] => 16:42:05
[Value] => 27.0
)
etc
Then in JS convert to json format to give me this
var ar = [{"Time":"16:37:36","Value":27.1},{"Time":"16:42:05","Value":27} etc
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time');
data.addColumn('number', 'Value');
data.addRows(ar);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 200});
When I run the script, all I get is a basic graph without any plotted data, just an empty graticule
Any pointers would be greatly appreciated
Your array needs to be changed from:
var ar = [{"Time":"16:37:36","Value":27.1},{"Time":"16:42:05","Value":27} etc
to (drop the '{', '"Time":' and '"Value":')
["16:37:36",27.1],["16:42:05",27] ,etc
For your Google LineChart see the example below
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawCurveTypes);
function drawCurveTypes() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time');
data.addColumn('number', 'Value');
data.addRows([
["16:37:36", 27.1], ["16:42:05", 27], ["16:44", 23], ["16:46", 17.0], ["16:51", 18], ["16:54", 9]
]);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Hits'
},
series: {
1: {curveType: 'function'}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
https://jsfiddle.net/api/post/library/pure/
Good day to everyone, I am trying to display a barchart that show the count of 2 different attribute with the name 'Feedback' VS 'Complain' and these two attribute are based on user selection.
I have followed some tutorial to create a Json file to same the data retrieve from mysql then to be display on the bar chart. So this is the data.php that receives the data based on query
<?php
//setting header to json
header('Content-Type: application/json');
$mysqli = mysqli_connect('localhost','root','','customercaremodule');
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query1 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Feedback'");
$Countsql1 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Feedback'";
//execute query
$result1 = $mysqli->query($query1);
$res1 = mysqli_query($mysqli,$Countsql1);
$value1 = mysqli_fetch_assoc($res1);
$feedbackrowcount = $value1['total'];
//loop through the returned data
$data1 = array();
foreach ($result1 as $row) {
$data1[] = $row;
}
//free memory associated with result
$result1->close();
//query to get data from the table
$query2 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Complain'");
$Countsql2 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Complain'";
//execute query
$result2 = $mysqli->query($query2);
$res2 = mysqli_query($mysqli,$Countsql2);
$value2 = mysqli_fetch_assoc($res2);
$complainrowcount = $value2['total'];
//loop through the returned data
$data2 = array();
foreach ($result2 as $row) {
$data2[] = $row;
}
//free memory associated with result
$result2->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data1);
print json_encode($data2);
print json_encode($feedbackrowcount);
print json_encode($complainrowcount);
?>
Then here is the script function I am facing a lot of challenge with. I am very new to Chart JS and PHP in general, if there's any security flaw please bear with me. THANK YOU FOR ANY KIND HELPERS
$(document).ready(function(){
$.ajax({
url: "http://localhost/customercare/data.php",
method: "GET",
success: function(data1) {
console.log(data1);
var feedback = [];
var complain = [];
for(var i in data1) {
feedback.push(data1[i].$feedbackrowcount);
}
success: function(data2) {
console.log(data2);
var feedback = [];
var complain = [];
for(var i in data2) {
feedback.push(data2[i].$complainrowcount);
}
var chartdata = {
datasets : [
{
label: 'Feedback',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: feedback
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data1) {
console.log(data1);
}
});
});
you can try to push in feedback an object, for example :
var bar_chart_obj_1 = {data: data1[i].$feedbackrowcount, label: "data1", id: 0};
feedback.push(bar_chart_obj_1);
var bar_chart_obj_2 = {data: $data2[i].$complainrowcount, label: "data2", id: 1};
feedback.push(bar_chart_obj_2);
I've to show a Google Chart in a loop . Without loop my chart works fine but when i try to add it in a loop i get it only for first iterataion , how do i fix it , please review this
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Daily Report'],
['Points Achieved', <?php echo $points_achieved?>],
['Points Left', <?php echo $points_left?>]
]);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" }
,height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<?php
$sql= "SELECT * FROM employees";
$query= mysqli_query($connection, $sql);
while($res= mysqli_fetch_assoc($query)): ?>
<div id='piechart'></div>
//other data from database comes here
<?php endwhile;?>
Since you are drawing multiple charts i would suggest to modify drawChart function to accept chart id and data as parameters:
function drawChart(chartId,data) {
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" },
height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById(chartId));
chart.draw(dataTable, options);
}
Then you could iterate PHP array and invoke drawChart function:
<?php
foreach ($reports as $key => $report) {
$chartId = "piechart_$key";
//prepare chart data
$chartData = array(
array("Task", "Daily Report"),
array("Points Achieved" , $report["Points Achieved"]),
array("Points Left" , $report["Points Left"])
);
?>
<div id='<?php echo $chartId; ?>'></div>
<script type="text/javascript">drawChart('<?php echo $chartId; ?>',<?php echo json_encode($chartData); ?>)</script>
<?php
}
?>
It is assumed $reports array has the following structure:
//input data example ( replace it with data retrieved from DB)
$reports = array(
"R1" => array("Points Achieved" => 20, "Points Left" => 4),
"R2" => array("Points Achieved" => 40, "Points Left" => 14),
"R3" => array("Points Achieved" => 10, "Points Left" => 0)
);
Working example
This is my second question about this problem:
I try to create a chart with Highcharts, but I can not fill the field "series" with the response returned from the server with PHP. The answer is in JSON format. The chart is not rendered, it goes white background. Thank you very much in advance.
I paste her the 3 codes:
SERVER SIDE PHP:
$arr = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$fecha = $row_RecordsetTabla['fecha'];
$hora = $row_RecordsetTabla['hora'];
$estado = $row_RecordsetTabla['estado'];
$arregloFecha = date_format(new DateTime($fecha),"Y,m,d");
$arregloHora = date_format(new DateTime($hora),"H,i");
$arr[] = array("Date.UTC(".$arregloFecha.",".$arregloHora.")", $estado);
}
$arr2[] = array('data' => $arr);
$json = json_encode($arr2);
echo str_replace('"', '', $json);
RESPONSE SERVER JSON:
[{data:[[Date.UTC(2014,03,27,12,00),2],[Date.UTC(2014,04,01,19,10),1],[Date.UTC(2014,04,01,15,44),1]]}]
CLIENT SIDE JAVASCRIPT HIGHCHARTS CODE:
$.get("mostrarStatsDispositivo.php", {idDispositivo:"2", numeroDispositivo:"hola"}, function(data){
chart = new Highcharts.Chart({
chart: {
renderTo: 'divStatsDispositivo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Gráfica de actividad'
},
tooltip: {
enabled: false,
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats : {
hour: '%H',
}
},
yAxis: {
categories: [ 'APAGADO', 'ACTIVO', 'ALARMA'],
title: {
text: 'ESTADO'
},
min: 0
},
series : [{
name : 'grafica',
type : 'line',
data : data[0].data //<-------thanks Barbara!
}]
});
});
The response JSON seems well formed..but dosn´t work...?¿ ....thanks!
EDIT: If i copy/paste the content of JSON in a variable, works fine. But i can´t put the value of JSON in a variable! ...doesn´t works! it´s posible?¿
FIXED!!!
Thanks Mr Jerko has detected (and solved) some errors in the code:
There is an error in a line of PHP file:
I put:
$arr2[] = array('data' => $arr);
and correct line is:
$arr2 = array('data' => $arr);
Another error to create a JSON line, and another error to put the data on "series:". check the responde under!
change your php file to look like this:
$arr = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$fecha = $row_RecordsetTabla['fecha'];
$hora = $row_RecordsetTabla['hora'];
$estado = $row_RecordsetTabla['estado'];
$arregloFecha = date_format(new DateTime($fecha),"Y-m-d");
$arregloHora = date_format(new DateTime($hora),"H:i");
$date = strtotime($arregloFecha . " " . $arregloHora) * 1000;
$arr[] = array($date, floatval($estado));
}
$arr2 = array('data' => $arr);
echo json_encode($arr2);
your JSON was in incorrect format because when you return Date.UTC(2014,03,27,12,00) without quotes it breaks format of json so you should convert your times to microseconds in php before echoing it.
also you would probably need to change your javascript line to
data: data.data
I am trying to build out a google chart in an mvc app.
Here is a snippet of google Chart javascript
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows([
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
}
what I would like to do is essentially replace the data.addRows line above with a for loop iterating through the items in my model. I can iterate just fine in the view outside of the tag like so of course:
"#foreach (var item in Model) {
<div>#Html.DisplayFor(modelItem => item.Customer.Name)</div>
}"
I cannot seem to find a solution to iterate through my model INSIDE a tag. Any ideas?
Assuming you have a view model:
public class MyViewModel
{
public object[][] Values { get; set; }
}
in which you store some values and pass along to the view:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Values = new[]
{
new object[] { "Work", 11 },
new object[] { "Eat", 2 },
new object[] { "Commute", 2 },
new object[] { "Watch TV", 2 },
new object[] { "Sleep", 7 },
}
};
return View(model);
}
}
in your view you could JSON encode it:
#model MyViewModel
<script type="text/javascript">
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows(#Html.Raw(Json.Encode(Model.Values)));
}
</script>
which will be rendered in the final markup as:
<script type="text/javascript">
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows([["Work",11],["Eat",2],["Commute",2],["Watch TV",2],["Sleep",7]]);
}
</script>
And you shouldn't be worried at all about having values that contain single or double quotes which could potentially break your javascript because you have used a JSON serializer instead of manually building it.