Can you make PHP and JS work together?
Moderator: General Moderators
Can you make PHP and JS work together?
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?
- NetDragonX
- Forum Newbie
- Posts: 15
- Joined: Sat May 25, 2002 3:00 pm
- Location: Southern California
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:
Hope this helps -
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>