p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/)
-   PHP FAQs (http://p2p.wrox.com/php-faqs-124/)
-   -   Q. How do I pass PHP variables to JavaScript? (http://p2p.wrox.com/php-faqs/11606-q-how-do-i-pass-php-variables-javascript.html)

Snib April 8th, 2004 12:34 PM

Q. How do I pass PHP variables to JavaScript?
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)


P2P Member

All times are GMT -4. The time now is 10:16 AM.

Powered by vBulletin®
Copyright ©2000 - 2018, Jelsoft Enterprises Ltd.
2013 John Wiley & Sons, Inc.