I am trying to input my Controller variable in ChartJS Javascript file to Dynamically create charts in ChartJS
Expression Expected at "<?"
Controller.php
public function index(Request $request)
{
#$result= DB::select("SELECT * FROM table WHERE user_id =?", [$user_id]);
$result_arr = json_decode(json_encode($result), true);
$label_array = array();
foreach($result_arr as $d)
{
$label_array[]=$d['label_element'];
}
$data_array = array();
foreach($result_arr as $d)
{
$data_array[]=$d['data_element'];
}
return view('home', ['labels'=>$label_array, 'data'=>$data_array]);
}
chart-pie-demo.js:
// Pie Chart Example
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: <?php echo json_encode($labels); ?>, // Error Line
datasets: [{
data: <?php echo json_encode($data); ?>, // Error Line
backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
hoverBorderColor: "rgba(234, 236, 244, 1)",
}],
},
Related
I'm new in Apexcharts, and I try to make a pie chart with data, getting from mysql database. This is the php-file named "get_types_chart.php"
$year = date('Y');
$month = date('m');
$graf = PDO()->prepare("SELECT COUNT(tickets.id) AS cid, types.ticket_type AS type_name FROM tickets LEFT JOIN types ON tickets.type=types.id WHERE tickets.arch=0 AND tickets.status NOT IN (2, 4) AND MONTH(tickets.date_create)=:month AND YEAR(tickets.date_create)=:year GROUP BY types.ticket_type");
$graf->execute([':year' => $year,
':month' => $month]);
$arrData = array();
while($row = $graf->fetch(PDO::FETCH_LAZY)) {
array_push($arrData, array(
"labels" => $row->type_name,
"series" => $row->cid
)
);
}
$jsonEncodedData = json_encode($arrData);
header('Content-Type: application/json');
echo $jsonEncodedData;
And this is the js-code:
var url3 = 'charts/get_types_chart.php';
var options3 = {
series: [],
chart: {
width: 380,
type: 'pie',
},
title: {
text: '<?php echo lang('MON_STAT_year'); ?>',
floating: true,
align: 'center'
},
labels: [],
responsive: [{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
position: 'bottom'
}
}
}]
};
var chart3 = new ApexCharts(document.querySelector("#chart3"), options3);
chart3.render();
$.getJSON(url3, function(response) {
chart3.updateSeries([{
name: '<?php echo lang('DASH_STAT_month_all'); ?>',
data: response
}])
});
Finally I get empty pie. Please hel me to make a correct json.
Hello so i try to retrieve data from a .php with Ajax to make a Doughnut chart with Chart.JS
Here is what i have (value 1, 2, 3, 4 in the legend order) :
This is my Chart.JS Script :
// Set new defawult font family and font color to mimic Bootstrap's default styling
Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';
$.ajax({
url:"./inc/pie_chart.inc.php",
method:"GET",
success:function(data) {
console.log(data);
var appelsnum =[1];
var mailsnum =[2];
var anomaliesnum =[3];
var decnum =[4];
// Pie Chart Example
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Appels", "Mails", "Anomalies", "DEC"],
datasets: [{
data: [appelsnum, mailsnum, anomaliesnum, decnum],
backgroundColor: ['#36b9cc', '#1cc88a', '#e74a3b', '#f6c23e'],
hoverBackgroundColor: ['#2c9faf', '#17a673', '#a3281c', '#dbac32'],
hoverBorderColor: "rgba(234, 236, 244, 1)",
}],
},
options: {
maintainAspectRatio: false,
tooltips: {
backgroundColor: "rgb(255,255,255)",
bodyFontColor: "#858796",
borderColor: '#dddfeb',
borderWidth: 1,
xPadding: 15,
yPadding: 15,
displayColors: false,
caretPadding: 10,
},
legend: {
display: false
},
cutoutPercentage: 80,
},
});
},
});
And this is my "pie_chart.inc.php" file (the one who Ajax is retrieving) :
<?php
header('Content-Type:text/plain');
require_once('./loggedin.inc.php');
require_once('./db.inc.php');
require_once('./settings.inc.php');
$sql="SELECT SUM(appels_res) AS totalsumappelsmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$appelsnum = mysqli_fetch_assoc($result);
$appelsnum = $appelsnum['totalsumappelsmonth'];
$sql="SELECT SUM(mails_res) AS totalsummailsmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$mailsnum = mysqli_fetch_assoc($result);
$mailsnum = $mailsnum['totalsummailsmonth'];
$sql="SELECT SUM(anomalies_res) AS totalsumanomaliesmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$anomaliesnum = mysqli_fetch_assoc($result);
$anomaliesnum = $anomaliesnum['totalsumanomaliesmonth'];
$sql="SELECT SUM(dec_res) AS totalsumdecmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$decnum = mysqli_fetch_assoc($result);
$decnum = $decnum['totalsumdecmonth'];
$data=array();
$data[0]=$appelsnum;
$data[1]=$mailsnum;
$data[2]=$anomaliesnum;
$data[3]=$decnum;
$result->close();
$conn->close();
print json_encode($data);
?>
When i'm visiting this page, there is what it's returning to me :
Theses are the good values that must be on the Charts.
However, i'm getting 1, 2, 3, 4.
Do you know how to fix this?
Thanks for reading :) Greetings.
You are getting 1,2,3,4 because they are hardcoded. Try changing
var appelsnum =[1];
var mailsnum =[2];
var anomaliesnum =[3];
var decnum =[4];
to
var appelsnum =[data[0]];
var mailsnum =[data[1]];
var anomaliesnum =[data[2]];
var decnum =[data[3]];
I have created a MySQL database and I am running xampp locally.
Here is my data.php:
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'products');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT date, url, price FROM table1");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
The output file generates the date, price and url
When I then take a look at my barchart.html, I am trying to introduce a onclick link to url when user clicks on each bar.
$(document).ready(function(){
$.ajax({
url: "http://192.168.64.2/fs/data.php",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var price = [];
for(var i in data) {
date.push("" + data[i].date);
price.push(data[i].price);
}
var chartdata = {
labels: date,
datasets : [
{
label: 'price',
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: price,
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
This is the bar chart which is generated;
When I hover over the bar chart, the date and price show up, however on click, I want to send user to url, as pulled from the table1 in data.php
I am using Laravel 5.6. I am trying to create a line chart graph using CHARTJS.
Here is the controller.
public function index()
{
$currentMonth = date('m');
$category = Category::where('isActive', 1)->count();
$product = Product::where('isActive', 1)->count();
$suppliers = Supplier::where('isActive', 1)->count();
$saleorderCount = SaleOrderDetail::count();
$sale_order_detail = SaleOrderDetail::whereRaw('MONTH(created_at) = ?',[$currentMonth])->get(['sale_order', 'grand_total']);
$data_points = SaleOrderDetail::select('sale_order', 'grand_total')->whereRaw('MONTH(created_at) = ?',[$currentMonth])->get();
$data_points = str_replace('sale_order', 'x', $data_points);
$data_points = str_replace('grand_total', 'y', $data_points);
$data_points = str_replace(',y:', '",y:', $data_points);
dd($data_points);
// dd($sale_order_detail);
return view('welcome', ['category' => $category, 'product' => $product, 'suppliers' => $suppliers, 'salecount' => $saleorderCount, 'sale_order_detail' => $sale_order_detail, 'data_points' => $data_points]);
}
With $data_points, passing value to view. Here is the script
<script type="text/javascript">
window.onload = function () {
var data_point = {!! $data_points !!};
console.log(data_point);
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: data_point,
datasets: [{
label: 'Sale of the Month',
data: data_point,
backgroundColor: [
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>
here is the console output of data points.
Here it how it show the chart.
Labels are not showing.
You're passing an array of objects for both your labels and your data. You want to pass an array of strings for the labels and an array of numeric values for your data. Change your code to this:
window.onload = function () {
var data_points = {!! $data_points !!};
//create your new arrays here
var data_labels = data_points.map((index) => index.x);
var data_values = data_points.map((index) => parseInt(index.y));
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//use data_labels array here
labels: data_labels,
datasets: [{
label: 'Sale of the Month',
//use data_values array here
data: data_values,
backgroundColor: [
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
i would like to send my data from mssql via php to my chart. For this i'm using $.get function to receive data from mssql.
but i'm getting an error: Uncaught TypeError: Cannot read property '0' of undefined obviously i can't access an object.
my php code:
if(isset($_GET['employeesChart'])) {
getemployeesChart($conn);
}
function getemployeesChart($conn) {
$sql ="SELECT * FROM employee;
$result = sqlsrv_query($conn, $sql);
$row = sqlsrv_fetch_array($result);
$isAtWork = $row['Work'];
$isAtHome = $row['Home'];
$data = array('isAtWork' => $isAtWork, 'isAtHome' => $isAtHome);
echo json_encode($data)
}
and my javascript code:
var data = {
labels: [
"Home",
"Work",
"Break"
],
datasets: [{
data: [],
backgroundColor: ["#FF6384","#36A2EB","#FFCE56"],
hoverBackgroundColor: ["#FF6384","#36A2EB","#FFCE56"]
}]
};
$.get("employees.inc.php?employeesChart", function(data){
var result = $.parseJSON(data);
var test = data.datasets[0].data.push(result[0],result[1]);
myDoughnutChart.update();
});
// Doughnut Chart
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
responsive: true,
legend: {
position: 'right',
},
animation: {
animateScale: true,
animateRotate: true
}
}
});
i don't understand why do i get an error. When i test it with console.log(result) im getting two integers but the code sample make data.datasets[0].data.push(result[0],result[1]) an error