Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET json data from a php file for an Angular scope

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>
like image 596
Michael Wilson Avatar asked Jul 31 '14 16:07

Michael Wilson


1 Answers

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.

like image 157
kiswa Avatar answered Nov 03 '22 06:11

kiswa