Thomas C Thomas C - 9 days ago 6
jQuery Question

How to ouput JSON in javascript?

I am trying to print the results of a json object from a php query into javascript.

So basically the query results looks like:

{"points":
[{"lat":40.766696929932,"long":-73.990615844727},
{"lat":40.688514709473,"long":-73.96475982666},
{"lat":40.714504241943,"long":-74.005630493164},
{"lat":40.704719543457,"long":-74.009262084961},
{"lat":40.693260192871,"long":-73.968894958496},
{"lat":40.760955810547,"long":-73.967247009277},

]}


When i try to get the php variable (using AJAX) containing the json object i get:

VM62:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1

I tried googling to see how the error relates to my code but i still don't get it.

Can someone explain to me how to get the json in javascript?

<?php
$connect = pg_connect("host=127.0.0.1 dbname=datab user=thomas password=iamtom") or die("Could not connect: ");
$result = pg_query($connect,"SELECT geometry FROM table");
if (!$result){
echo '{"error":"no results"}';
}

$points= array();
while($row = pg_fetch_array($result)){
$coordinate = json_decode($row['geometry'])->coordinates;
$p = new stdClass;
$p->lat = $c_2[0];
$p->long = $c_1[1];
array_push($points, $p);
}
$output = new stdClass;
$output->points = $points;
echo json_encode($output);
pg_close($connect);
?>


Here is my HTML/JS:

<html>
<head>
<title>Simple Map</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>
$.ajax({
type: "GET",
dataType: "JSON",
url: "dab.php",
data: {
sataVariable: "here is some data send with GET method"
},
success: function(data) {
var j = JSON.parse(data);
document.writeln(data); // attempting to take the coordinates and store it in a variable
},
error: function(data) {
console.log(data);
}
});
</script>
</head>
<body>

</body>
</html>

Answer

Because you're feeding dataType: "JSON" into your call to jQuery.ajax() the data retrieved from the AJAX call is automatically being parsed from JSON to a JavaScript object (though I'd switch "JSON" to "json" to match the documentation):

"json": Evaluates the response as JSON and returns a JavaScript object.

Don't manually parse the response again using JSON.parse() in your success handler; just work directly with data.

Now that you have your data in a JavaScript object called data you can interact with it, e.g.

for (var i = 0; i < data.points.length; i++) {
    console.log(data.points[i].lat, data.points[i].long);
}