Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Joe Bruno
35,909 PointsAccess Key-Value pairs of JS Object returned via Ajax from PHP Function
Hello Everyone,
I have a PHP function being called via Ajax and successfully returning data. The responseText is the following (as printed out by console.log() ):
"Array
(
[0] => Array
(
[key] => test_4Kteld
[name] => Company1
)
[1] => Array
(
[key] => test_eb53yLF
[name] => Company2
)
)"
How can I access each of the "key" and "name" value pairs with Javascript?
I have tried many variations of
var key = text[0].key;
and consulted stackoverflow and beyond, but I am having trouble getting this to work. Help?
Thanks,
3 Answers
Agapito Cruz
21,486 PointsHello Joe,
Have you tried converting the responseText into an array using
someArray = JSON.parse(responseText); and then accessing it through the array like so:
someArray[0]["key"] ?
Let me know if this helps.
-Agapito
Joe Bruno
35,909 PointsHello Agapito,
I did actually, and all it keeps returning is an unexpected token error "A" referring to the "Array" keyword that begins the JSON response. How do I get past this?
Agapito Cruz
21,486 PointsHi Joe,
Try having your PHP format the responseText like https://www.JSON.com suggests:
{ "myArray": [ "a", "b", "c", "d" ] }
and see if that helps.