Cory Crowley Cory Crowley - 3 years ago 224
AngularJS Question

Error Fetching Data From a PHP Server Running MySQL with Angular JS

I am getting a [$http:baddata] error when my Angular app calls my php file.
I'm not sure where the error is triggering exactly, but I believe it's a problem constructing the json object! I've attached all relevant code. Any help would be amazing. Thanks in advance :)

enter image description here

Angular documentation shows this
enter image description here

This is the PHP file which connects to my database and attempts to return a JSON formatting string back to the calling file

echo '<script>console.log("Inside php file!")</script>';
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");


$query = "SELECT rideid, destination, price, capacity, userid, origin, departDate, vehicle FROM rides";

$result = @mysqli_query($dbc, $query);

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Origin":"' . $rs["origin"] . '",';
$outp .= '"Destination":"' . $rs["destination"] . '",';
$outp .= '"Price":"'. $rs["price"] . '"}';
$outp .= '"Capacity":"'. $rs["capacity"] . '"}';

$outp ='{"records":['.$outp.']}';
//echo '<script>console.log(JSON.stringify('.$outp.'))</script>';


This is the Angular app making the request to the PHP file

<!-- Include Angular -->
<script src=""></script>

<!-- Ride Table -->
<div ng-app = "rideAppTest" ng-controller= "rideCtrlTest">
<tr ng-repeat = "x in names">
<!-- End Ride Table -->

<!--Ride Table Script-->
var app = angular.module('rideAppTest', []);
app.controller('rideCtrlTest', function($scope, $http) {
function (response) {
$scope.names =;
console.log("Error!" + data);


Answer Source

Don't construct the JSON the way you are doing, first collect everything inside an array or an object then do echo json_encode($result);

Something like this:

$outp = [];
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    $outp[] = $rs;
echo json_encode(["records" => $outp]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download