Brandon J Brandon J - 6 days ago 6
Ajax Question

How to output string as a json in Javascript?

I am trying to get the results of a query from php into a javascript object. So in the console i see an error message Uncaught SyntaxError: Unexpected token { in JSON at position 66. I know this is because i am trying to read a json when the variable is a string. So heres my dilemma. Below are the query results of a text column called thestartgeom which contains geojson objects (latitude and longitude):

{"type":"Point","coordinates":[40.752067565918,-73.9678421020508]}
{"type":"Point","coordinates":[40.6908912658691,-73.9961242675781]}
{"type":"Point","coordinates":[40.7666969299316,-73.9906158447266]}


The reason why i store it as a text column is because there are over 100,000 records in the database and i am trying to select only the distinct rows. I know this is a text column but i want to read it as a json object in javascript so i can go row by row and output the latitude and longitude(40.342,-73.221). Forgive me if i offend any one with my question but this is really annoying me and SO is my last resort.

My ultimate goal is to output only the coordinates of the object in javascript.

Below is my code and Any help would be greatly appreciated.

My php file:

<?php

$connect = pg_connect("host=127.0.0.1 dbname=d106 user=b16 password=cccC") or die("Could not connect: ");
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bike");
if (!$result)
{
echo "no results ";
}

while($row = pg_fetch_array($result))
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>


My HTML/JS:

<html>
<head>
<title>Simple</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 r = data.responseText;
var j = JSON.parse(r);
var coords = j.coordinates;

document.writeln(coords); // attempting to take the coordinates and store it in a variable
for (i = 0; i < coords.length; i++) {
coords.forEach(function(entry){
// loop through the coordinates and output the lat,lng
var d = document.getElementById("fpcoords");
d.innerHTML = d.innerHTML + "<br>" + "LatLng(" + entry[0] + "," + entry[1] + "));"
});

}
}
});
</script>
</head>
<body>
</body>


</html>

Answer

Your first JSON is invalid, the three objects need to be inside an array, meaning you need to surround them with [ ] and separate them with commas, i would also reformat your JSON a bit, just to limit the amount of unnecessary data:

<?php
$connect = pg_connect("host=127.0.0.1 dbname=d106 user=b16 password=cccC") or die("Could not connect: ");
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bike");
if (!$result){
    echo '{"error":"no results"}';
}

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

Working PHP Sandbox: http://sandbox.onlinephpfunctions.com/code/0d3c4081edf097190e7233dc49b3f84cbe0ed094

This will output your JSON as such:

{
 "points": [
   {
     "lat": 40.752067565918,
     "long": -73.9678421020508
   },
   {
     "lat": 40.6908912658691,
     "long": -73.9961242675781
   },
   {
     "lat": 40.7666969299316,
     "long": -73.9906158447266
   }
 ]
}

Then simply iterating over them in Javascript like this:

var dataset = /* The JSON above... */
var pointList = document.getElementById('pointList');

dataset.points.forEach(function(p){
  var li = document.createElement('li');
  li.innerHTML = "LatLong: "+p.lat+", "+p.long;
  pointList.appendChild(li);
});

A working JSFiddle: https://jsfiddle.net/workingClassHacker/qkpp333z/1/

Comments