Ariana Ariana - 1 year ago 1422
AngularJS Question

SyntaxError: Unexpected token < in JSON at position 0 at Object.parse (native) (AngularJS)

I'm successfully saving my data into a json file with a php script (save-data.php) but I'm unable to fetch it correctly with my get-data.php script.

Error message: angular.js:12520 SyntaxError: Unexpected token < in JSON at position 0 at Object.parse (native)



$json = file_get_contents("php://input");

$file = fopen('C:/test/save-data.json','w+');

fwrite($file, $json);





//header('Content-Type: application/json');

$json = file_get_contents('C:/test/save-data.json');

//Decode JSON
//$json_data = json_decode($json, true);

//Print data
echo $json



"id": "179",
"var1": "variable1",
"var2": "variable2"

sample controller:

// save data (myModel: id, var1, var2)
$ = function() {
console.log('Creating a JSON');
$scope.jsonString = angular.toJson($scope.myModel, true);
$'save-data.php', $scope.jsonString).then(function(data) {
$scope.msg1 = 'Data saved';
$scope.msg2 = 'Data sent: '+ $scope.jsonString;

// get data
$scope.get = function() {
$http.get('get-data.php').then(function(data) {
//$scope.my_data = JSON.parse(data);

EDIT: I didn't need to decode the json file to json nor to parse it (all commented in scripts).

Answer Source

Invariably, 99.9999999% of the time you get Unexpected token < in JSON as position 0 in the error, you did NOT receive json from the server. You received an HTML error message with your json following afterwards.

<p>PHP warning: blah blah blah</p>

The leading < in the <p>... is where the error comes from, because that's position 0 (first character).

Check the raw data coming back from the server, and fix whatever the error/warning that PHP is spitting out.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download