Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.