9

I'm trying to get json data from a php file to use within an Angular controller. Im echoing json_encode(pg_fetch_assoc($result)); within the php file and when I console.log($scope.contents); in the angular controller it brings back the json data, but it comes back empty when I try doing an ng-repeat

controllers.js:

myApp.controller('ContentCtrl', function ($scope, $http) {
  $http({method: 'GET', url: 'content.php'}).success(function(data) {
    $scope.contents = data;
  });
});

content.php:

<?php
require_once("sdb.php");
$result = pg_query($dbconn, "SELECT * FROM content ORDER BY name ASC");
echo json_encode(pg_fetch_assoc($result));

index.php:

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body ng-app="myApp">
 <div ng-controller="ContentCtrl">
   <ul>
     <li ng-repeat="content in contents">
       <a href="#">{{content.name}}</a>
     </li>
   </ul>
 </div>
</body>
   <script src="js/jquery-1.10.2.js"></script>
   <script src="js/angular.min.js"></script>
   <script src="js/controllers.js"></script>
</html>

1 Answer 1

19

You'll want to actually send the data as JSON. To do that, you just need to add header('Content-Type: application/json'); before your echo statement. So content.php becomes:

<?php
require_once("sdb.php");

$result = pg_query($dbconn, "SELECT * FROM content ORDER BY name ASC");

header('Content-Type: application/json');
echo json_encode(pg_fetch_assoc($result));

As an aside, there are a few things you may want to do with your controller. I would change this:

myApp.controller('ContentCtrl', function ($scope, $http) {
    $http({method: 'GET', url: 'content.php'}).success(function(data) {
        $scope.contents = data;
    });
});

to this:

myApp.controller('ContentCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('content.php')
    .success(function(data) {
        $scope.contents = data;
    });
}]);

The additional '$scope', '$http', before the function definition allows you to minify in the future, and the .get is just personal preference, but I think it's cleaner to read.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fast answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.