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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

hmmm now I get Unexpected token a..!? (when I parse twice)
Then response isn't the value you claim it to be: 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 to learn more about how to access objects to get the value you want.
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.
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
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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.