Brandon J Brandon J - 7 days ago 6
Javascript Question

loading PHP into Javascript

I am trying to output the query into a javascript object. I searched the internet for articles on how to get this done but i can't seem to understand.
The query is done in the php code below. My question is how do i output the results from a php variable into a javascript object? Can someone guide me as to how to get this done? Note I have the slightest of knowledge of how to go about doing this so please bare with me.

<?php

$connect = pg_connect("host=127.0.0.1 dbname=bis user=bran6 password=cbrat") or die("Could not connect: ");
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bike");
if (!$result)
{
echo "no results ";
}
$data[];
while($row = pg_fetch_array($result))
{

$data[] = $row['the_start'];

}

pg_close($connect);
?>

<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDbIwQc21ErxhqyY_B1lXB4yOMTEDsNGCQ&">
</script>
<script>

var ar =<?php echo json_encode($data)?>;

writeln(ar);
</script>
</head>

</body>
</html>


When i look at the console I receive a Uncaught SyntaxError: Unexpected token <.

Answer

Your code has some markups errors.

First, where is your <body> opening tag?

Second, you're running an writeln function wrongly, the correct way is to document.writeln

Also, your <?php echo json_encode($data)?> is returning something that javascript can't handle, so, the error: Uncaught SyntaxError: Unexpected token is being throw

Comments