0

I have a PHP script which is used for a POST request which returns (echos) the array:

array(3) {
  ["message"]=>
  string(32) "The item was successfully saved"
  ["newItemId"]=>
  int(9)
  ["newCustomFieldIds"]=>
  string(3) "[9]"
}

My AJAX request:

$.ajax({
        url: 'updateItemDetails.php',
        method: 'post',
        data: {
            ...
        }
    }).done(function(response) {
            console.log(response); //correct
            console.log(response['newCustomFieldIds']); //undefined
            console.log(JSON.parse(response['newCustomFieldIds'])); //unexpected token u
    });

The first console.log produces:

{"message":"The item was successfully saved","newItemId":9,"newCustomFieldIds":"[9]"}

which is as expected. However, the second one gives undefined.

So, when I JSON.parse, I get Uncaught SyntaxError: Unexpected token u! What I'm trying to do is to get the "[9]" to a real array, ie. [9].

I don't understand this. newCustomFieldIds definitely exists, because when logging the response, I can see it -- so why doesn't the console.log(response['newCustomFieldIds']) work?

ᔕᖺᘎᕊ
  • 2,971
  • 3
  • 23
  • 38

1 Answers1

2

You have to parse response:

JSON.parse(response).newCustomFieldIds

If you want to convert the string "[9]" to an array, you need to call JSON.parse twice:

JSON.parse(JSON.parse(response).newCustomFieldIds)

However, the better solution would be to encode the value of newCustomFieldIds as an array in the first place, i.e. the JSON should contain "newCustomFieldIds": [9].


Since you know that response['newCustomFieldIds'] returns undefined, it doesn't make sense to try JSON.parse(response['newCustomFieldIds']). It's the same as JSON.parse("undefined"), but undefined is not valid JSON.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • hmmm now I get `Unexpected token a`..!? (when I parse twice) – ᔕᖺᘎᕊ Feb 13 '16 at 21:00
  • Then `response` isn't the value you claim it to be: https://jsfiddle.net/bu63quzb/ . The general solution is pretty straightforward: If you have a string that contains JSON, call `JSON.parse`. Read [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) to learn more about how to access objects to get the value you want. – Felix Kling Feb 13 '16 at 21:03
  • That means the `response` also contains `"array(3) => ..."` which is not valid JSON. It seems you have a `var_dump` somewhere in your PHP code. That output is also sent to the client as part of the response. Remove it. – Felix Kling Feb 13 '16 at 21:08
  • oh! you're right!! I have it a few changes back which is what I use to echo the data back! I should have removed that ages ago! Thank you so much!! :D – ᔕᖺᘎᕊ Feb 13 '16 at 21:11
  • And I think it's worth the effort to encode it as an array in the first place, so I'll probably go back and change anything I need to to do that. Thanks again :) – ᔕᖺᘎᕊ Feb 13 '16 at 21:11