Jump to content

[FAQ] How do I pass PHP variables to javascript?


Recommended Posts

JavaScript cannot actively read variables from the server, but when a page loads, PHP can pass variables to JavaScript by writing to the page the JavaScript is on.



   $username = "Snib";
<script language="javascript" type="text/javascript">
   var sStr = "My name is <?php echo $username ?>.";



This code will output this text:



My name is Snib.



By editing the JavaScript on the page, PHP can set JavaScript variables.

This is very useful for passing database values to JavaScript to compare with a JavaScript variable or number. Let's say that there is a MySQL database called db1, with a table called table1, which has two columns, 'userid' and 'usernum'. To retrieve information about Snib, you can use code like this:



   $connection = mysql_connect('localhost', 'username', 'password');

   $sql = mysql_select_db('db1', $connection);

   $userid = "Snib";

   $query = "SELECT * FROM `table1` WHERE userid='$userid'";

   $result = mysql_query($query);

   $data = mysql_fetch_assoc($result);

   $usernum = $data['usernum'];


<script language="javascript" type="text/javascript">

   var userid = "<?php echo $userid; ?>";

   var usernum = "<?php echo $usernum; ?>";

   //if usernum is less than or equal to 50
   if (usernum <= 50) { 

       alert("You are not allowed on this page, " + userid);
       setTimeout('window.location = "otherpage.php"', 3000); // user leaves in 3 seconds

   } else {

       alert('Welcome to this page, ' + userid);



<?php mysql_close($connection); ?>


Although setting JavaScript variables with PHP is helpful, it cannot always be done. For instance, PHP cannot modify external .js documents temporarily. It changes them for good.


MySQL with PHP: http://php.net/mysql

JavaScript: http://javascript.com http://msdn.microsoft.com/library/default.asp (JScript and DHTML)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...