I am Trying to make a HighChart's Line Chart Based on the data from the Database.
I Fetched the Data from The Database as I can see that data in the console .
The php Code I Used is :
<?php
$query = "
SELECT YEAR(created_at) AS year,
MONTHNAME(created_at) AS month,
COUNT(*) AS count
FROM users
GROUP BY month ASC ORDER BY created_at ASC
" ;
$result = mysqli_query($conn, $query) ;
while ($row = mysqli_fetch_assoc($result)) {
$data1[] = $row['month'];
$data2[] = $row['count'];
}
?>
Now I Fetched the Data in Highchart's script as Follows :
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
type: 'line',
},
title: {
text: 'Download Trends'
},
credits: {
enabled: false
},
xAxis: {
categories: ['<?php echo join($data1, "','"); ?>'],
},
yAxis: {
min: 0,
title: {
text: 'No. of Downloads'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Qty',
data: ['<?php echo join($data2, "','"); ?>'],
}]
});
});
</script>
I using the container div with id container as follows :
<div id="container"></div>
The Problem is that the data is not showing in correct Manner . its been showing only half of the data as you can see below :
its not showing the Line.
Please Help
Your data serie is made of strings, and Highcharts works with numbers for this kind of graph.
Remove the simple quotes in the data section and it should works :
data: [<?php echo join($data2, ","); ?>]
I want to load the ChartJs Chart after an ajax call. But unfortunately, it showing Undefined variable errors for all ChartJS php variables.
Target:
Change the chart based on user select from the dropdown list, each selection option is basically a JSON link from where we fetch the data to show with chartjs.
What I have done so far:
Setup an AJAX call which works ok for each user select both "default"
on page load plus "on change" options.
Added Chartjs code after the successful ajax request section.
Tested all JSON codes & php data its all working ok.
All ajax return data for chartjs php variables are ok.
Issues:
Undefined variable error for all chartjs PHP variables (name,
cot_labels,
cot_values,cot_values2,cot_values3,cot_values4,cot_values5)
No data showing on chart.
Chart also not refreshing with new data when user select another option.
Here is the Javascript part:
$(document).ready(function(){
$.ajax({
url: "./url.php",
type: "POST",
data: {
cur: $("#cur").val()
},
success: function(data) {
alert(data);
new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: [<?php echo '"'.$cot_labels.'"'; ?>],
datasets: [{
data: [<?php echo $cot_values; ?>],
label: "A",
borderColor: "#3e95cd",
fill: false
}, {
data: [<?php echo $cot_values2; ?>],
label: "B",
borderColor: "#8e5ea2",
fill: false
} ,
{
data: [<?php echo $cot_values3; ?>],
label: "C",
borderColor: "#085b83",
fill: false
} ,
{
data: [<?php echo $cot_values4; ?>],
label: "D",
borderColor: "#1c2925",
fill: false
} ,
{
data: [<?php echo $cot_values5; ?>],
label: "E",
borderColor: "#b9801d",
fill: false
}
]
},
options: {
title: {
display: true,
text: '<?php echo $name; ?>'
},
animation: {
duration: 0, // general animation time
},
hover: {
animationDuration: 0, // duration of animations when hovering an item
},
responsiveAnimationDuration: 0, // animation duration after a resize
}
});
}
});
$('#cur').on('change', function() {
$.ajax({
url: "./url.php",
type: "POST",
data: {
cur: $("#cur").val()
},
success: function(data) {
alert(data);
new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: [<?php echo '"'.$cot_labels.'"'; ?>],
datasets: [{
data: [<?php echo $cot_values; ?>],
label: "A",
borderColor: "#3e95cd",
fill: false
}, {
data: [<?php echo $cot_values2; ?>],
label: "B",
borderColor: "#8e5ea2",
fill: false
} ,
{
data: [<?php echo $cot_values3; ?>],
label: "C",
borderColor: "#085b83",
fill: false
} ,
{
data: [<?php echo $cot_values4; ?>],
label: "D",
borderColor: "#1c2925",
fill: false
} ,
{
data: [<?php echo $cot_values5; ?>],
label: "E",
borderColor: "#b9801d",
fill: false
}
]
},
options: {
title: {
display: true,
text: '<?php echo $name; ?>'
},
animation: {
duration: 0, // general animation time
},
hover: {
animationDuration: 0, // duration of animations when hovering an item
},
responsiveAnimationDuration: 0, // animation duration after a resize
}
});
}
});
});
});
<select id="cur" name="cur">
<option value="<?php echo $euro;?>">EURO</option>
<option value="<?php echo $pound;?>">UK</option>
</select>
<canvas id="line-chart" width="800" height="450"></canvas>
Here is the PHP Part:
$euro = "URL";
$pound = "URL";
//AJAX CALL
if (isset($_POST['cur'])) {
$cur = filter_input(INPUT_POST, 'cur', FILTER_SANITIZE_STRING);
//Build arrays
$cot_label_arr = array();
$cot_value_arr = array();
$cot_value_arr2 = array();
$cot_value_arr3 = array();
$cot_value_arr4 = array();
$cot_value_arr5 = array();
$json=file_get_contents($cur);
$data = json_decode($json);
foreach ($data as $item ) {
$name = $item->name;
// echo $item->newest_available_date;
foreach($item as $value => $value_1){
if (is_array($value_1) || is_object($value_1))
{
foreach($value_1 as $value_2 ){
if (is_array($value_2) || is_object($value_2))
{
$cot_label_arr[] = date('M j Y',strtotime($value_2[0])); //pull dates
$cot_value_arr[] = $value_2[1];
$cot_value_arr2[] = $value_2[2];
$cot_value_arr3[] = $value_2[3];
$cot_value_arr4[] = $value_2[4];
$cot_value_arr5[] = $value_2[5];
}
}
}
}
}
$cot_labels = array_reverse($cot_label_arr); //reverse the data for ASC
$cot_values = array_reverse($cot_value_arr); //reverse the data for ASC
$cot_values2 = array_reverse($cot_value_arr2); //reverse the data for ASC
$cot_values3 = array_reverse($cot_value_arr3); //reverse the data for ASC
$cot_values4 = array_reverse($cot_value_arr4); //reverse the data for ASC
$cot_values5 = array_reverse($cot_value_arr5); //reverse the data for ASC
//----
$cot_labels = implode('","', $cot_labels); //comma sep
$cot_values = implode(", ", $cot_values); //comma sep
$cot_values2 = implode(", ", $cot_values2); //comma sep
$cot_values3 = implode(", ", $cot_values3); //comma sep
$cot_values4 = implode(", ", $cot_values4); //comma sep
$cot_values5 = implode(", ", $cot_values5); //comma sep
exit;
} // End of ajax call
If I use echo $cot_values; inside the ajax call, then I get to see correct data. But chartjs is not loading with it. Here is the screenshot of what I get returned for $cot_values.
Not sure why I am getting undefined data error for chartjs php variables whereas I am calling the chartjs javascript after the successful ajax call. Plus why the correct data is not loading on the chart.
UPDATE: with MLStud coding
Now no longer undefined php chartjs variable error as we are using java json data. But the chart is not loading, in the place of the chart a white blank space is showing. I have tested all data for any kind of wrong format, but it was ok.
Here is the updated coding part:
PHP:
if (isset($_POST['cur'])) {
........
$cot_labels = implode(", ", $cot_labels); //edited as it was showing date with extra ""
$cot_values = implode(", ", $cot_values); //comma sep
$cot_values2 = implode(", ", $cot_values2); //comma sep
$cot_values3 = implode(", ", $cot_values3); //comma sep
$cot_values4 = implode(", ", $cot_values4); //comma sep
$cot_values5 = implode(", ", $cot_values5); //comma sep
// New added
$result = array(
'cot_labels'=>$cot_labels,
'cot_values'=>$cot_values,
'cot_values2'=>$cot_values2,
'cot_values3'=>$cot_values3,
'cot_values4'=>$cot_values4,
'cot_values5'=>$cot_values5,
'name'=>$name
);
print_r(json_encode($result));
exit;
} // End of ajax call
Javascript + HTML :
$(document).ready(function(){
var ctx = document.getElementById("myChart").getContext('2d');
$.ajax({
url: "./url.php",
type: "POST",
data: {
cur: $("#cur").val()
},
success: function(data) {
alert(data);
var datos = JSON.parse(data);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: datos.cot_labels, ///in this way you access the data of the returned json
datasets: [{
data: datos.cot_values,///in this way you access the data of the returned json
label: "A",
borderColor: "#3e95cd",
fill: false
}, {
data: datos.cot_values2,
label: "B",
borderColor: "#8e5ea2",
fill: false
}]
},
options: {
title: {
display: true,
text: data.name
},
animation: {
duration: 0, // general animation time
},
hover: {
animationDuration: 0, // duration of animations when hovering an item
},
responsiveAnimationDuration: 0, // animation duration after a resize
}
});
}
});
$('#cur').on('change', function() {
$.ajax({
url: "./url.php",
type: "POST",
data: {
cur: $("#cur").val()
},
success: function(data) {
var datos = JSON.parse(data);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: datos.cot_labels, ///in this way you access the data of the returned json
datasets: [{
data: datos.cot_values,///in this way you access the data of the returned json
label: "A",
borderColor: "#3e95cd",
fill: false
}, {
data: datos.cot_values2,
label: "B",
borderColor: "#8e5ea2",
fill: false
}]
},
options: {
title: {
display: true,
text: data.name
},
animation: {
duration: 0, // general animation time
},
hover: {
animationDuration: 0, // duration of animations when hovering an item
},
responsiveAnimationDuration: 0, // animation duration after a resize
}
});
}
});
});
});
<select id="cur" name="cur">
<option value="<?php echo $euro;?>">EURO</option>
<option value="<?php echo $pound;?>">UK</option>
</select>
<canvas id="myChart" width="800" height="450"></canvas>
For more further verification here is the date format how it looks like: (when we call it after successful ajax call)
alert(datos.cot_labels);
To take the value of variables you have to access the json obtained as an answer (data) and you have to convert "val1, val2, ..." in the vector [val1, val2, ...] with split:
var ctx = document.getElementById("myChart").getContext('2d');
$.ajax({
url: "server.php",
type: "POST",
data: {
...
},
success: function(data) {
var datos = JSON.parse(data);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: datos.cot_labels.split(','), ///in this way you access the data of the returned json
datasets: [{
data: datos.cot_values.split(','),///in this way you access the data of the returned json
label: "A",
borderColor: "#3e95cd",
fill: false
}, {
data: datos.cot_values2.split(','),
label: "B",
borderColor: "#8e5ea2",
fill: false
}]
},
options: {
title: {
display: true,
text: datos.name
},
animation: {
duration: 0, // general animation time
},
hover: {
animationDuration: 0, // duration of animations when hovering an item
},
responsiveAnimationDuration: 0, // animation duration after a resize
}
});
}
});
Result:
I'm trying to plot some data using javascript , ajax and php .
This is my test.php :
$query=sprintf("SELECT COUNT( `cases_title`) as count ,`cases_title` FROM `classifies` GROUP BY `cases_title`");
$result=$mysqli->query($query);
$data=array();
foreach($result as $row){
$data[]=$row;
}
$result->close();
$mysqli->close();
print json_encode($data);
?>
I printed the output and it was :
[{"count":"7","cases_title":"ANGINA"},{"count":"1","cases_title":"ASTHMA"},{"count":"4","cases_title":"MI"}]
So I suppose test.php is working.
This is my app.js :
$(document).ready(function(){
$.ajax({
url: "http://localhost/final/test.php",
method: "GET",
success: function(data) {
console.log(data);
var cas=[];
var cou=[];
// document.write(data);
for(var i in data) {
cas.push(data[i].cases_title);
cou.push(data[i].count);
}
console.log(cou);
var chartdata = {
labels: cas,
datasets : [
{
label: 'Count',
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: cou
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
document.write(data) in app.js returns : [{"count":"7","cases_title":"ANGINA"},{"count":"1","cases_title":"ASTHMA"},{"count":"4","cases_title":"MI"}]
However the arrays aren't being filled. They show as undefined . The url to test.php is correct.
What is causing the arrays cou and cas to not be filled? I couldn't figure it out.
you have to parse the response as json with JSON.parse(data) or the other side arround JSON.stringify before transferring valid json data via network.
I wanted the chart's labels and data to be dynamic.
To get things started, I have a function called search in my Controller and it has a query like this:
$total_cost = DB::raw('SUM(qty * cost) as total_cost');
$total_grossrev = DB::raw('(SUM(price * qty)) as total_grossrev');
$total_profit = DB::raw('(SUM(price * qty)) - (SUM(qty * cost)) as total_profit');
$period = DB::raw('date(created_at) as period');
$format = 'j F Y h:i A';
$salesanalysis = DB::table('orders')
->whereDate('created_at','>=', $request->datefrom)
->whereDate('created_at', '<=', $request->dateto)
->where('status', 'served')
->select($total_cost, $total_grossrev, $total_profit, $period, 'created_at')
->groupBy('period')
->get();
And in my script to have the chart, this is my structure:
<script src="{{ asset('js/Chart.min.js') }}"></script>
<script>
let salesAnalysisChart = document.getElementById('salesAnalysisChart').getContext('2d');
let barChart = new Chart(salesAnalysisChart, {
responsive: true,
type:'bar',
data:{
labels:[ //period of salesanalysis ],
datasets:[{
label:'Sales',
data:[
// total_profit of salesanalysis
],
backgroundColor: 'rgba(73, 187, 235, 0.7)',
hoverBorderWidth: 1,
hoverBorderColor: '#000'
}]
},
options:{
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
},
legend:{
position:'bottom',
display:false,
},
layout:{
padding: 0,
}
}
});
</script>
Also, the period of salesanalysis is gonna be parsed by Carbon with the use of $format. So I thought of using this syntax:
{{\Carbon\Carbon::parse($collection->period)->format($format)}}
The bottomline is, how am I gonna use the collection for the label and data of ChartJs.
At the bottom of the view create a buildChart function that takes the labels, data, and any other as paremeters. Pass them over using the PHP implode method and return the imploded variable in blade to a function that creates chart.
//View
buildChart({{ $variable }}, ect)
Somehow I managed to solve the problem.
In my controller, I did a query and converted it into array:
$salesanalysisarray = DB::table('orders')
->whereDate('created_at','>=', $request->datefrom)
->whereDate('created_at', '<=', $request->dateto)
->where('status', 'served')
->select($total_cost, $total_grossrev, $total_profit, $period, 'created_at')
->groupBy('period')
->get()
->toArray();
And in my script, I initialized another array and did a loop to push each data into the array itself:
var periodArray = new Array();
var profitArray = new Array();
var costArray = new Array();
#forelse($salesanalysis as $analysis)
periodArray.push("{{\Carbon\Carbon::parse($analysis->created_at)->format($format)}}");
profitArray.push("{{$analysis->total_profit}}");
costArray.push("{{$analysis->total_cost}}");
#empty
#endforelse
Im new in Js and Jquery and I have a curiosity about the Jquery Chart that is free to download and I want to make the data inside to be coming from the database to make it dynamic but somehow I find it difficult to loop it in.
here is my sample code, I used PHP to get the database and pass it on a JS variable
<!DOCTYPE HTML>
<html>
<head>
<?php
$link = mysqli_connect("localhost","root","","raksquad_centralized") or die("Error " . mysqli_error($link));
if($link->connect_error){
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM raksquad_centralized.grade";
$result = $link->query($query);
$subject_id= array();
$genAve = array();
while($row = mysqli_fetch_array($result)){
$subject_id[] = $row['subject_id'];
$genAve[]= $row['gen_ave'];
}
?>
<script type="text/javascript">
window.onload = function () {
var DataXAxis = <?php echo json_encode($subject_id); ?>; // X axis that corresponds to students
var DataYAxis = <?php echo json_encode($genAve); ?>; // Y axis that corresponds to grades
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Top Students"
},
animationEnabled: true,
axisY: {
title: "Grades"
},
axisX: {
title: "Students"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "General Average",
dataPoints: [
//the area to loop with the value of DataXAxis, DataYAxis
{y: 98, label: "MT1234" },
{y: 72, label: "MT1236"} //corresponds to the barcharts
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="./canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
appreciate for the help, useful for learning :)
I just use a php code to fetch the data, then json encode it.
On the script use json parse