Skip to content

Instantly share code, notes, and snippets.

@niczak niczak/gist:882246
Created Mar 22, 2011

Embed
What would you like to do?
Example of how to use PHP data w/ JavaScript functions
<?php
// Connect to database
$hDB = pg_connect("connection_parms_go_here");
// Grab list of tags
$hRes = pg_query($hDB, "SELECT sTag FROM tags WHERE bActive ='t' ORDER BY sTag");
pg_close($hDB);
// Store dataset in an array
$aRes = pg_fetch_all($hRes);
$sTags = NULL;
// Walk array and build up tag string
foreach($aRes as $aRec)
{
foreach($aRec as $sTag)
$sTags .= "\"$sTag\",\n";
}
// Trim last ",\n" from string
$sTags = rtrim($sTags, ",\n");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript/PHP Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(function()
{
var aTags = [
<?php
// Populate JavaScript array w/ data from PHP variable.
echo $sTags;
?>
];
// do stuff
});
</script>
</head>
<body>
<div id="container">
<!-- page container -->
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.