I am trying to create charts, using data from MySQL in my JS file.
So :
- I receive data in my JS script calling my PHP file.
- My connection works (PHP).
- I convert datas in JSON.
- I get datas back in my JS file.
- And I can display them into my HTML file/page
With :
`<div ng-repeat="x in users" align="center">
<div class="col-md-4" >
<div class="showProfile">
{{x.TotalCall}}
</div>
</div>
</div>`
My PHP code :
<?php
$dbhost="localhost";
$dbuser="root";
$dbpass="";
$dbname="callstats";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $dbh->query("SELECT extension, COUNT(*) AS TotalCall, COUNT(CASE WHEN billsec >= 20 THEN billsec END) AS 'moreThanTwenty' FROM pbx GROUP BY extension");
$query = $query->fetchAll(PDO::FETCH_ASSOC);
$myJson = json_encode($query);
echo "{\"records\":".$myJson."}";
?>
My AngularJS file :
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("php/DBbitrix.php")
.then(function(response) {
$scope.users = response.data.records;
});
var ctxP = document.getElementById("pieChart").getContext('2d');
var myPieChart = new Chart(ctxP, {
type: 'pie',
data: {
labels: ["Red", "Green", "Yellow", "Grey", "Dark Grey"],
datasets: [
{
//data: [angular.forEach($scope.userListe, function(value){console.log(value.TotalCall)})],
data: [ angular.forEach($scope.users, function (value,TotalCall){TotalCall + ": " + value})],
backgroundColor: ["#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360"],
hoverBackgroundColor: ["#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5", "#616774"]
}
]
},
options: {
responsive: true
}
});
});
So, in my pieChart, if the data is [20,50,60,80,100] for example, it's going to work.
In my database, I have a TotalCall table with numbers values that I want to use in my "data : []" . Because in my HTML, values are correctly displayed, I would like to know how I can dirrectly use the JSON datas in my JS file.
I am trying since 3 days, I found a lot of solutions, for example with angular.foreach, but it doesn't work. I don't understand why this is so complicated to just use a JSON field.
I tried to display values in the console with :
var users = $scope.users;
console.log(users);
console.log("t");
console.log($scope.users);
angular.forEach($scope.users, function (value,TotalCall){console.log(TotalCall + ": " + value.TotalCall);})
console.log(angular.forEach($scope.users, function (value,TotalCall){TotalCall + ": " + value}));
console.log(angular.forEach($scope.users, function (value,TotalCall){value}));
console.log(angular.forEach($scope.users, function (value,TotalCall){value.TotalCall}));
But the value is "undefined" and I don't get the data I want.
Sorry if I made mistakes, I am still learning English and it's my first post on stackoverflow.