Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?

I recived data by ajax

<?
 $locations[] = array(
'Name'=>$name,
'Latitude'=>$lat,
'Longitude'=>$long};
print_r(json_encode($locations));
?>

Here I have error, becasu it doesn't show anything when I tried with alert(data) and it work and show the array json that is below

success:function(data) {
  var dat =$.parseJSON(data);
   $("#pru").html(dat.Name); //here it doesn't show anything if I put alert(data) it show me all the array json
}

the array json content, the next array:

[{"Name":"Jayme jayden","Latitude":"36.712005","Longitude":"-4.43825"},
{"Name":"Jhonny","Latitude":"36.728744","Longitude":"-4.443822"},
{"Name":"Jessica Lynn","Latitude":"36.7418","Longitude":"-4.4333 "}]
share|improve this question
3  
$("#pru").html(resp[0].Name); Edit: + read Joseph's answer – Peter Jan 28 at 1:12
It is already parsed, you just have to access it properly. – Felix Kling Jan 28 at 1:13
2  
@Peter Szymkowski I already changed $("#pru").html(dat[0].Name) and it doesn't work – Kakitori Jan 28 at 1:14
1  
Do you know what the brackets in $locations[] = do? – fab Jan 28 at 1:16
@FelixKling - How? Unless the server is sending valid JSON headers (which I doubt) or the data type is set to JSON (which the OP has not shown), how would it already be parsed? – Joseph Silber Jan 28 at 1:17
show 1 more commentadd comment (requires an account with 50 reputation)

marked as duplicate by Felix Kling, George Stocker Jan 28 at 1:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

up vote 4 down vote accepted

You shouldn't use print_r to send JSON. Just do a regular echo:

$locations = array(
    'Name' => $name,
    'Latitude' => $lat,
    'Longitude' => $long
);

echo json_encode($locations);

You also have a syntax error in your code (the closing brace for the array), and I think you're unintentionally creating a multi-dimensional array. Use the code above, and it should work.

share|improve this answer
Technically right but it does not make a difference, since json_encode always returns a string and print_r on strings just behaves like print/echo. – fab Jan 28 at 1:14
@fab - True, which is why I also point out 2 other problems in the code. – Joseph Silber Jan 28 at 1:15
1  
Yes, after you edited it, the answer is great – fab Jan 28 at 1:18
1  
yep, it work now, thanks! – Kakitori Jan 28 at 1:18
add comment (requires an account with 50 reputation)

Not the answer you're looking for? Browse other questions tagged or ask your own question.