0

First of all, thanks in advance for any help. I have been struggling for a couple of days trying to figure out how to hook an angular-chart object into a mysql database. I currently have the charts working with static data. I have a generic php file in my project that looks something like this:

// Create the connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";

//the sql to run
$sql = "SELECT * FROM Test2";
//run it
$result = $conn->query($sql);

//check for results
if ($result->num_rows > 0) {
//create an array
$dataarray[] = array();

//loop em
while($row =mysqli_fetch_assoc($result)) {
    $dataarray[] = $row;
}
//make em json
echo json_encode($dataarray);
}
//} else {
//    echo "0 results";
//}

//close out our connection
$conn->close();
?> 

This works fine. This table returns a couple of rows with the headers Name and Value. Nothing but test data at this time.

In my html/javascript, I have the following:

<script>
        angular.module("ChartApp", ["chart.js"]).controller("PieCtrl", function ($scope, $http) {
          $http.get('./GetTestData.php').
            success(function(data) {
                $scope.records = data;

            });

          $scope.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales"];
          $scope.data = [300, 500, 100];
        });
    </script>

I am not really sure where to go from here. Any help would be appreciated.

Pikuchan
  • 11
  • 4

2 Answers2

0

Took forever, but I finally figured it out. I had to take the JSON object and convert the values out into separate arrays. Here is the relevant code:

angular.module("ChartApp", ["chart.js"]).controller("PieCtrl", function ($scope, $http) {
 $http.get('./GetTestData.php').
success(function(data) {
    var names = [];

    for(var i = 0; i < data.length; i++) {
        var obj = data[i];

        if(obj.Name != undefined) {
            names.push(obj.Name);
        }
    }

    var values = [];
    for(var i = 0; i < data.length; i++) {
        var obj = data[i];

        if(obj.Name != undefined) {
            values.push(obj.Value);
        }
    }
    //$scope.records = data;
    $scope.labels = names;
    $scope.data = values;
    });

        });
    </script>
Pikuchan
  • 11
  • 4
0

I was getting the follow error with that code:

Uncaught TypeError: Cannot read property 'draw' of undefined

So I had to insert [ and ] at $scope.data to make it works.

$scope.labels = names;
$scope.data = [values];
Jazi
  • 6,569
  • 13
  • 60
  • 92
Guilherme Teubl
  • 1,136
  • 11
  • 11