1

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! The JSON issue

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);
}
RP McMurphy
  • 704
  • 8
  • 30
  • 2
    If you are sending back a JSON, you normally don't even need to use JSON.parse() - just ensure to include the correct [header](https://stackoverflow.com/a/4064468/1022914). You may also think about simplifying by using [$.getJSON()](http://api.jquery.com/jquery.getjson/). – Mikey Jan 12 '18 at 19:24
  • JSON.stringify(data) logs this- "[{\"id\":\"394857\",\"fips\":\"6097\",\"county\":\"SONOMA\",\"date_year\":\"1995\",\"age\":\"12\",\"pop_male\":\"2986\",\"pop_female\":\"3252\"}]" – RP McMurphy Jan 12 '18 at 19:29
  • I'd suggest to set correct "Accept" headers as @Mikey suggested, so that jQuery will do JSON.parse for you. Then I'd suggest using Debugger and see your data on the each step https://developers.google.com/web/tools/chrome-devtools/javascript/ – Oleg Andreyev Jan 12 '18 at 19:32
  • In your Chrome browser, analyze your response. Inspect > Network tab > XHR > click the request > look at Response Headers' Content-Type. It should say `application/json`. – Mikey Jan 12 '18 at 19:33
  • 1
    If you explicitly set `dataType: 'JSON'` in your `.ajax` options, then you don't need to parse the response, as it will already be an object to use. Default is 'smart', which may have already turned it into an object as well, thus trying to json.parse an object will result in ... not good data. – IncredibleHat Jan 12 '18 at 19:33
  • Please show your PHP code where you are outputting your response. – IncredibleHat Jan 12 '18 at 19:35
  • $sql = "SELECT * FROM `pop_proj`"; $query = $this->db->query($sql); $result = $query->result(); return json_encode($result); As @Musa suggested in the answer below, double JSON.parse() fixes this. What is the standard procedure then? – RP McMurphy Jan 12 '18 at 19:37
  • 1
    "Standard procedure" is to (1) set the header and (2) use echo/print as shown in this [answer](https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script/4064468#4064468). – Mikey Jan 12 '18 at 19:40

1 Answers1

4

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.

Musa
  • 96,336
  • 17
  • 118
  • 137
  • If the OP has to resort to using not just one but two `JSON.parse()` I would bet that his response is not coming back as a JSON. – Mikey Jan 12 '18 at 19:28
  • This works and fixes the undefined problem! I am requesting mysql to serve me the records, I json_encode() the result with php and in the ajax end JSON.parse them and the undefined problem shows up. When I double JSON.parse(), the problem goes away. Should I not JSON.parse or should I not json_encode() with php? Where am I double encoding? – RP McMurphy Jan 12 '18 at 19:32
  • 1
    it would have to be somewhere in your php code, post it so we can see – Musa Jan 12 '18 at 19:34
  • $sql = "SELECT * FROM pop_proj"; $query = $this->db->query($sql); $result = $query->result(); return json_encode($result); Here it is. – RP McMurphy Jan 12 '18 at 19:37
  • This looks like some kind of framework you're using, what is it and update the question with the code, the full function. – Musa Jan 12 '18 at 19:42