What am I doing wrong? I have this JSON.parse error: unexpected character at line 1 column 1 of the JSON data

1

I'm doing an exercise with PHP and Angular JS, the complete error is this:

And I vote just when I'm making a query, I use a controller.js and two php, one is read_products that serves as an intermediary and the other is products, in which I do all the query to the database. I do not know what I'm doing wrong, since I saw it in a tutorial but I could not resolve this error.

controller.js

$scope.getAll = function(){
            $http.get("read_products.php").success(function(response){
                $scope.names = response.records;
            });
        }

read_products.php

<?php 
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8"); 
 
// include database and object files 
include_once 'config/database.php'; 
include_once 'objects/product.php'; 
 
// instantiate database and product object 
$database = new Database(); 
$db = $database->getConnection();
  
// initialize object
$product = new Product($db);
  
// query products
$stmt = $product->readAll();
$num = $stmt->rowCount();
  
// check if more than 0 record found
if($num>0){
      
    $data="";
    $x=1;
      
    // retrieve our table contents
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        // extract row
        // this will make $row['name'] to
        // just $name only
        extract($row);
          
        $data .= '{';
            $data .= '"id":"'  . $id . '",';
            $data .= '"name":"' . $name . '",';
            $data .= '"description":"' . html_entity_decode($description) . '",';
            $data .= '"price":"' . $price . '"';
        $data .= '}'; 
          
        $data .= $x<$num ? ',' : ''; $x++; } 
} 
 
// json format output 
echo '{"records":[' . $data . ']}'; 
?>

products.php / function for the query

function readAll(){
 
    // select all query
    $query = "SELECT 
                id, name, description, price, created 
            FROM 
                " . $this->table_name . "
            ORDER BY 
                id DESC";
 
    // prepare query statement
    $stmt = $this->conn->prepare( $query );
     
    // execute query
    $stmt->execute();
     
    return $stmt;
}
    
asked by Emiliano Lara 09.08.2016 в 19:44
source

1 answer

1

PHP has a method to serialize JSONs.
The response you are sending is not (although in yes format).
In the header you should specify it as a JSON (Content-Type → application / json; charset = utf-8).

In order not to be elbowing this, better consult the PHP documentation to serialize correctly.

Look here: json_encode

    
answered by 22.08.2016 в 23:37