0

I have sat behind this all day. I am building a plug in and i am including angular js.

So far all is well but i am not able to get a php file to read from database and pass values to angular js

file.php

<?php
global $wpdb;
$table_name = $wpdb->prefix . 'workout';

$results = $wpdb->get_results(" SELECT title FROM $table_name ");

$arr=[];
$i=0;

foreach($results as $r)
{
$arr[$i]['title'] = $r->title;
$i++;
}

echo json_encode($arr);
//echo '[{"title":"Demo Title"},{"title":"Demo Title"},{"title":"Demo Title"}]';

The way i know my code works is that when i uncomment the last part of my code above the code works. so for some reason the json serialisation is not working properly, also the commented code is what both echo json_encode($arr); and echo json_encode($results); return. Why is angularjs giving me nothing? What am I doing wrong here.

controller.js

var app = angular.module('myApp', []);

app.controller('workoutCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get(params.url)
        .success(function(data) {
            $scope.records = data;
        });
}]);

Table

echo '<div ng-app="myApp" ng-controller="workoutCtrl">';
echo '<table class="table">';
echo '<thead>';
echo '<tr >';
echo '<th>Title</th>';
echo ' </tr>';
echo ' </thead>';
echo ' <tbody>';
echo '  <tr ng-repeat = "x in records">';
echo '    <td>{{x.title}}</td>';
echo '  </tr>';
echo ' </tbody>';
echo ' </table>';
echo '</div>';
flexxxit
  • 2,440
  • 5
  • 42
  • 69

1 Answers1

-1

You need to set response header in php

header('Content-Type: application/json');
echo json_encode($arr);
Dhiren
  • 592
  • 5
  • 16
  • so why does it work with hard code data? This is good suggestion but isn't going to resolve problem – charlietfl Mar 08 '16 at 15:37
  • Because you are sending a stringified response when sending in plain text. – Dhiren Mar 08 '16 at 15:38
  • Please reverse the negative vote. Check out the related answer http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script – Dhiren Mar 08 '16 at 15:41