mellis95 Posted May 18, 2011 Share Posted May 18, 2011 I am attempting to use JSON.parse for my first time today and I am having trouble figuring out what is going on. I have the following PHP code: while ($row = $query->fetch(PDO::FETCH_ASSOC)) { $dataArray[] = $row; } echo json_encode($dataArray); Which passes the following data to the client (viewed with Chrome Developer Tools): [{"coord":"23","data":"PATIENT NAME"},{"coord":"127","data":"PATIENT NAME"}] I have the following javascript code (snippet) to process the JSON: if(httpObject.readyState == 4) { if (httpObject.status == 200) { x = JSON.parse(httpObject.responseText); alert(x); } } The alert I get is: [object Object],[object Object] I have been on Google for quite a while trying to figure this out, and everything that I have read says that the following code should just work: x = JSON.parse(httpObject.responseText); alert(x.coord); If I try to access the array key (x.coord OR x.coord[0]) I get "undefined". What am I missing here? I bet it is something simple. (It usually is...) Thanks in advance for the help. Matt Quote Link to comment Share on other sites More sharing options...
KevinM1 Posted May 18, 2011 Share Posted May 18, 2011 Have you tried alert(x[0].coord); ? Quote Link to comment Share on other sites More sharing options...
requinix Posted May 18, 2011 Share Posted May 18, 2011 x is an array so the first thing you need is a numeric offset like x[0]. That value is an object. x will mimic the $dataArray you had in your PHP code. If you would type $dataArray[0]["coord"] in PHP then you would use x[0]["coord"] in Javascript. (But because x[0] is an object, x[0].coord works as well.) Quote Link to comment Share on other sites More sharing options...
mellis95 Posted May 18, 2011 Author Share Posted May 18, 2011 WOW. I knew it would be something easy. Thank you for the help. x[0].coord is just what I needed. Matt Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.