Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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:

<?phprequire_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.

Post a Comment for "Get Json Data From A Php File For An Angular Scope"