Jump to content

JSON.parse not working as I expect?


mellis95

Recommended Posts

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

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/236787-jsonparse-not-working-as-i-expect/
Share on other sites

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.)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.