Can you make PHP and JS work together?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
MattSharp
Forum Commoner
Posts: 62
Joined: Wed Apr 24, 2002 2:25 pm

Can you make PHP and JS work together?

Post 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?
User avatar
NetDragonX
Forum Newbie
Posts: 15
Joined: Sat May 25, 2002 3:00 pm
Location: Southern California

Post 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 -
Post Reply