3

I'm hanging dry here. The user clicks on an option on a select list, then jQuery sends an xhr to the server to process, nothing special here, code works perfectly (firebug shows correct Posted data).

Then a simple code to return rows from a database where W_id == $val, and then fetch results in $result, then echo results as a json response:

public function getCities($val) {
    $sth = $this->db->prepare("SELECT id, name FROM cities WHERE w_id = :w_id");
    $sth->execute(array(':w_id' => $val));
    $result = $sth->fetchAll(PDO::FETCH_ASSOC);
    //print_r($result);
    header("content-type:application/json");
    echo json_encode($result);
}

Firebug shows the Post data but no Response. But when I uncomment the print_r, it shows me an array as a Response:

Array(
    [0] => Array(
        [id] => 1401
        [name] => Aïn Bouchekif
    )

    [1] => Array(
        [id] => 1402
        [name] => Aïn Deheb
    )

    [2] => Array(
        [id] => 1403
        [name] => Aïn El Hadid
    ) and so on...

Which means that there are results that can be returned, but I don't know how to jsonify them. Any help is appreciated, thanks.

hiddeneyes02
  • 2,562
  • 1
  • 31
  • 58

2 Answers2

2

I think it's an encoding problem, you can verify this idea by using json_last_error(). You can add charset=utf-8 to the header :

$result = $sth->fetchAll(PDO::FETCH_ASSOC);
//print_r($result);
header("Content-type: application/json; charset=utf-8"); // <-- Here
echo json_encode($result);
echo json_last_error(); // <-- Here
JC Sama
  • 2,214
  • 1
  • 13
  • 13
  • With echo json_last_error(); success method is fired up, and I have 5 as a Response. Manual says it's Malformed UTF-8 characters, possibly incorrectly encoded, I guess it's because of the ï – hiddeneyes02 Feb 11 '15 at 18:44
1

Here is what worked for me: UTF-8 character encoding battles json_encode()

public function getCities($val) {
    $sth = $this->db->prepare("SELECT id, name FROM cities WHERE w_id = :w_id");
    $sth->execute(array(':w_id' => $val));

    header("Content-type: application/json; charset=utf-8");

    $rows = array();

    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        $rows[] = array_map('utf8_encode', $row);
    }

    echo json_encode($rows);
}

I found other answer here How to json_encode array with french accents? but keeps getting notices, illegal character found.

Community
  • 1
  • 1
hiddeneyes02
  • 2,562
  • 1
  • 31
  • 58