Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode not working on PDO fetched data

Tags:

jquery

ajax

php

pdo

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.

like image 689
hiddeneyes02 Avatar asked May 27 '26 07:05

hiddeneyes02


2 Answers

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
like image 101
JC Sama Avatar answered May 30 '26 07:05

JC Sama


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.

like image 33
hiddeneyes02 Avatar answered May 30 '26 05:05

hiddeneyes02



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!