1

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?

Leohom
  • 13
  • 5

2 Answers2

3

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • so amazing! It's exactly what my problem is, My JSON is wrong! but it comes out another bug $scope.trans first get Promise {$$state: Object} and factory.js return JSON later should I wait the response like [this post](http://stackoverflow.com/questions/18421830/how-to-wait-till-the-response-comes-from-the-http-request-in-angularjs)? – Leohom Jul 02 '15 at 09:50
  • I got the solution! That's asynchronous problem, just follow [this post](http://stackoverflow.com/questions/18421830/how-to-wait-till-the-response-comes-from-the-http-request-in-angularjs). Thank you!!! – Leohom Jul 02 '15 at 13:45
-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
                });
  • There's an ajax call in the code in the question already. It just uses the angular ajax library (which you should definitely be using when you use angular — replacing it with jQuery is not a good idea). – Quentin Jul 02 '15 at 09:30
  • i tried and it finally no error pop up in console but the returned data is not my data in php it returned Object {readyState: 1} thank you for your help! – Leohom Jul 02 '15 at 09:33