i3ick February 2016

Can't figure out why AngularJS doesn't read JSON from PHP

I've spent hours trying to figure this out and browsing the web, but I must be doing something wrong. Every time i load the page it's just blank. I'm trying to load the database from mysqli to angularjs. The code is copied exactly from W3 exercises so I have no idea where the problem is.

dbaseread.php is in the same folder as the html.

PHP:

 $query = "SELECT * FROM members";
    $result = $mysqli->query($query);
    $r = array();
    if( $result->num_rows>0){
    while($row = $result->fetch_assoc()){
    $r[] = $row;
    }
    }


    $res = json_encode($r);

    header('Content-Type: application/json');

    echo $res;

HTML

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul>
  <li ng-repeat="x in myData">
    {{ x.name }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
  $http.get("dbaseread.php").then(function (response) {
      $scope.myData = response.data.records;
  });
});
</script>

</body>
</html>

Answers


i3ick February 2016

try $scope.myData = response.data. Doesn't look like any records property in the php. Inside the then can put console.log(response.data) then look in browser console at what is actually returned

– charlietfl

There indeed wasn't any 'records' property, so removing it fixed the issue.

Post Status

Asked in February 2016
Viewed 3,023 times
Voted 10
Answered 1 times

Search




Leave an answer