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?

2
  • have you tried an online json validator? there are 100's Commented Jul 2, 2015 at 9:20
  • validator said [ { id: 0, title --------------^ Expecting 'STRING', '}' should I change it to string? Commented Jul 2, 2015 at 9:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
I got the solution! That's asynchronous problem, just follow this post. Thank you!!!
-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
                });

2 Comments

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).
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.