JSON.parse: unexpected end of data

Viewed 814

I am new to Angularjs and SlimPHP and I have some troubles parsing my datas to json. I just started a new application and I can't figure out why this is not working.

Here is the function of my controller that seems to be working (I can use print_r to display $poles), but cannot return Json. In Network on Firefox, I have the mistake: "SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data".

public function getPoles($request, $response) {

    $poles = $this->container['form.dao']->getPoles();
    if ($poles == null) {
        return json_encode(["error" => "no data found"]);
    }

    return $response->withJson($poles, 200);
}

The getPoles() function from formDAO.php:

    public function getPoles() {
    $request =  "SELECT * FROM menu_pole ORDER BY id";
    try {
        $stmt = $this->db->query($request);
        $poles = $stmt->fetchAll(\PDO::FETCH_OBJ);
        return $poles;
    } catch(\PDOException $e) {
        return '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

I guess I may be missing something obvious.

EDIT:

With print_r, I get this:

 Array(
[0] => stdClass Object
    (
        [id] => 1
        [libelle] => GE
    )

[1] => stdClass Object
    (
        [id] => 2
        [libelle] => GP
    )

[2] => stdClass Object
    (
        [id] => 3
        [libelle] => GS
    )

[3] => stdClass Object
    (
        [id] => 4
        [libelle] => NO
    )

[4] => stdClass Object
    (
        [id] => 5
        [libelle] => DH
    )

[5] => stdClass Object
    (
        [id] => 6
        [libelle] => CRC
    )

[6] => stdClass Object
    (
        [id] => 7
        [libelle] => SG
    ))
2 Answers

Return json like this:

public function getPoles($request, $response) {

    $poles = $this->container['form.dao']->getPoles();
    if ($poles == null) {
        $data['error'] = 'no data found';
        return json_encode($data);
    }

    return $response->withJson($poles, 200);
}

I think I found the origin of the problem. In the array, I did not copy the full "libelle" field because they were quite long. I just realized that this is the problem, because as the datas are in French, they have so many accents that are not supported.

I just needed to update this line of my db connection:

    $db = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
Related