Home JSON.parse() in AJAX response says undefined, why?
Reply: 1

JSON.parse() in AJAX response says undefined, why?

RP McMurphy
1#
RP McMurphy Published in 2018-01-12 19:19:57Z

I have been working on this little app which sends an AJAX GET request to an URL which gives a JSON reply with PHP json_encode() function and when I try to access any individual response JSON value, it says undefined but the console.log() of the whole response gives me VALID JSON!

What am I doing wrong here please?

UPDATE with code: The code is written using Codeigniter. Here is the server side code.

public function getByIdModel($id){
    $sql = "SELECT * FROM `pop_proj` WHERE `id`= $id";
    $query = $this->db->query($sql);
    $result = $query->result();
    return json_encode($result );
} 
public function getByIdController() {
    $this->load->model('Crud_model');
    $query = $this->Crud_model->getById('394857');

    echo json_encode($query);
}
Musa
2#
Musa Reply to 2018-01-12 20:07:09Z

It looks like data is a string, that would mean response is double encoded.

Try var data = JSON.parse(JSON.parse(response));

If that works go to your server side code and fix the double encoding and ofcourse remove the double parsing on the client side.


I'm guessing getById calls getByIdModel both calls json_encode, I would remove it from getByIdModel so your data isn't encoded twice.


With respect to the whole json parsing point, if your ajax request expects json set the dataType parameter to JSON and then the response in your success function will parsed to their JavaScript native type.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.337931 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO