Leohom
Leohom

Reputation: 13

AngularJS ajax with PHP json return

I am new with php and angularjs >< I am trying to using ajax to get the data from php but fail

here's my controller

angular.module('AA')
    .controller('ExpController', ['$scope', 'Record', '$http', function ($scope,Record, $http) {
    $scope.trans = [];
    $scope.trans = Record.all();
}]);


factory.js

    angular.module('AA')
    .factory('Record', ['$http',function RecordFactory($http){
      return{
        all: function(){
            return $http.get("./php/getdata.php").success(function (response) {
              return  response;
            });
        }
      }
}]);


./php/getdata.php

<?php
header("Content-Type: application/json; charset=UTF-8");
$response=
      ' [
        {id: 0, title: "help", date: "1288323623009", cost: 20, person:"hard", category:"angu", items:[ {name:"item1"},{name:"item2"},{name:"item3"}]},
        {id: 1, title: "hahah", date: "1288323623008", cost: 9.99, person:"Leo", category:"adv"}
      ]';

echo ($response);
?>

console said

SyntaxError: Unexpected token i
at Object.parse (native)
at fromJson.....

is my json format wrong?

Upvotes: 1

Views: 1124

Answers (2)

This might work.

1.Yes have an ajax call to the php from angular.

var responsePromise = $http.get("./php/getdata.php");

responsePromise.success(function(data, status, headers, config) {
                   //Assign resultJSON to desired variable
                });

Upvotes: -2

Quentin
Quentin

Reputation: 944083

Your response isn't JSON, so the JSON parser in the browser is failing.

Property names must be strings. Strings must be delimited with double quotes.

{id:{"id": (and so on for all your other properties).

Use a linter to test your JSON.

Don't write JSON by hand. Create a PHP data structure and then pass it through json_encode.

Upvotes: 3

Related Questions