Page 1 of 1

Can you make PHP and JS work together?

Posted: Sun May 26, 2002 2:20 pm
by MattSharp
Is it possible to use something I get through PHP in a JavaScript. Like I want to retrieve something from a database and then use it in a JavaScript. If so, what would be the best way to do this?

Posted: Sun May 26, 2002 2:41 pm
by NetDragonX
Sure, since PHP is server-side and JavaScript is client-side (in most cases), you can just pump some code in PHP that the server will look through and parse first, then you can use JavaScript all you want.

For example:

Code: Select all

<?php
$db = mysql_pconnect("localhost","user","pass");
$q = "SELET bgColor FROM settings LIMIT 0,2";
$results = mysql_query($q, $db);

// Initiate client-side JavaScript
echo "<SCRIPT Language='JavaScript'>";

$i = 0;
while ( $row = mysql_fetch_object($results) )
{
   // JavaScript can be treated like normal output here to set up client-side
   // variables. Just remember to properly escape special chars.
   echo "var color".$i." = ".$row->bgColor.";<br>";
   $i++;
}
echo "</SCRIPT>";

// Now you can use the variables you parsed with JS
?>

</HEAD>

<BODY>

<SCRIPT Language="JavaScript">
document.write("<DIV BGCOLOR="+color0+">1st background</DIV>");
document.write("<DIV BGCOLOR="+color1+">2nd background</DIV>");
document.write("<DIV BGCOLOR="+color2+">3rd background</DIV>");
</SCRIPT>

</BODY>

</HTML>
Hope this helps -