Thomas C Thomas C - 1 year ago 117
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:



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?

$connect = pg_connect("host= 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);

Here is my HTML/JS:

<title>Simple Map</title>
<script src=""></script>

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


Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download