niczak
3/22/2011 - 10:38 PM

Example of how to use PHP data w/ JavaScript functions

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>