unable to parse json client side...

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
aayushraj
Forum Newbie
Posts: 1
Joined: Wed Apr 28, 2010 1:36 pm

unable to parse json client side...

Post by aayushraj »

Hi,
I have created a nested JSON object using the following php code :

Code: Select all

while($row = $result->fetch_assoc())
		{
			$fname = $row['uname'];
			$name = getName($fname);
			
			$temp = array(name=>$name, fname=>$fname);
			$ret_val[] = json_encode($temp);
		}
		
		return json_encode($ret_val);
Now I am processing this json in Javascript(using jQuery) as follows:

Code: Select all

function(data)  // data contains the JSON object
{	
       alert(data);
	//alert(data.result);
	//alert(result.length);
	for(var i=0;i<data.length;i++)
	{
		var obj = data[i];
		alert(obj);
		for(var key in obj)
	        {
			alert(key);
		}	
	}
}
alert(data) gives th following output : {"name":"Apurv Prakash","uname":"aprakash"},{"name":"xyz","uname":"abc"},{"name":"XYZ1","uname":"ABC1"} while I think it should give the following output :
[ {"name":"Apurv Prakash","uname":"aprakash"},{"name":"xyz","uname":"abc"},{"name":"XYZ1","uname":"ABC1"}] // Extra square brackets at the beginning and end.
If this is so then what should I change in the PHP code.

alert(obj) is giving output : {"name":"Apurv Prakash","uname":"aprakash"} then {"name":"xyz","uname":"abc"} and so on....

but alert(key) is giving the following output : 0 1 2 3..... instead of the expected name and uname....

I am not sure if the error is in PHP code or the JS code...

I have been stuck on this since past two days.. Please help...
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: unable to parse json client side...

Post by VladSun »

How about:

Code: Select all

while($row = $result->fetch_assoc())
{
		$ret_val[] = array
		(
			name	=> getName($fname), 
			fname	=> $row['uname']
		);
}
                
return json_encode($ret_val);
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply