piitr
piitr

Reputation: 35

AngularJS ng-repeat not showing data in table

I have a problem with output from MySQL

getCustomers.php is

$query="select distinct c.ancestry, c.trusted from members c order by c.id";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    $arr[] = json_encode($row);
}
}

# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;

and controler code:

app.controller('customersCrtl', function ($scope, $http, $timeout) {
$http.get('ajax/getCustomers.php').success(function(data){
    $scope.list = data;
    $scope.currentPage = 1; //current page
    $scope.entryLimit = 100; //max no of items to display in a page
    $scope.filteredItems = $scope.list.length; //Initially for no filter  
    $scope.totalItems = $scope.list.length;
});
$scope.setPage = function(pageNo) {
    $scope.currentPage = pageNo;
};
$scope.filter = function() {
    $timeout(function() { 
    $scope.filteredItems = $scope.filtered.length;
    }, 10);
};
$scope.sort_by = function(predicate) {
    $scope.predicate = predicate;
    $scope.reverse = !$scope.reverse;
};
});

Problem is that i get from MySQL this format (e.g.):

["{\"ancestry\":\"12865794218\",\"trusted\":\"128\"}"]

but expectable is:

[{"ancestry":"1286794218","trusted":"126"}]

so, if I write constants in data it works perfectly fine

$scope.list = [{"ancestry":"1286794218","trusted":"126"}];

Thanks for any help.

Upvotes: 0

Views: 152

Answers (3)

Don't Panic
Don't Panic

Reputation: 41820

You're double-encoding your response. The backslashes are there because the second application of json_encode escapes the double quotes in the output of the first one. Remove the json_encode from inside your while loop.

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $arr[] = $row;                        // don't encode here
    }
}

Then just encode it once afterward (as you already are.)

$json_response = json_encode($arr);

Upvotes: 1

Fotis
Fotis

Reputation: 1362

I think you need to use header('Content-Type: application/json'); in your php code, so that the server responds with a JSON content type.

There is also a duplicate json_encode in your code, inside your while loop so you're doing duplicate json encoding, hence the unexpected output

Upvotes: 1

Vic
Vic

Reputation: 424

use JSON.parse() on your response. JSON.parse docs

Upvotes: 0

Related Questions