Skip to content

Instantly share code, notes, and snippets.

@niczak
Created March 22, 2011 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niczak/882246 to your computer and use it in GitHub Desktop.
Save niczak/882246 to your computer and use it in GitHub Desktop.
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