I have a Postgresql database on the server side. I’d like to load data on it for display on a HTML webpage. How would I go about being able to get access to this data in javascript? Are there any tutorials out there? It seems like this would be a common thing to have done but so far I can’t seem to find out how to do it. I did find some stackoverflow questions about using php and node.js to do it but I can’t seem to get that working. php seems to be like the easiest way to do it, and I copied some code from another question, but it doesn’t seem to work.
var patientData = [];
var patient_id = 8;
<?php
$connection = pg_connect("connectstuff");
if(!$connection)
{
pg_close($connection);
}
$result = pg_query($connection, "query");
if (!$result)
{
exit;
}
$row = pg_fetch_row($result, 0);
echo "patientdata = $row;";
echo "alert('asdf')";
?>
The alert isn’t even getting shown, so I don’t think the php code is even running.
Check the source of the generated page, and make sure that the
$rowvalue you’re outputting is actual syntatically valid javascript. E.g. if it’s an array representing a row of data, php will actually outputArray, not some value from that row.beyond that, when using PHP to dynamically built javascript, you should ALWAYS use json_encode() to ensure that the PHP variables you’re inserting into the javascript come out as valid javascript. The slightest little syntax error in the inserted data will kill the entire JS code block, and you’ll end up where you are now – a dysfunctional page and no idea why it died:
will 100% guarantee that whatever you’re inserting into the JS code will NOT cause a parser error. Whether the data will actually work with your code is another matter, but at least the script won’t get killed at the parsing stage.