How to pass value from database to javascript?
PHP is a server-side script while javascript is a client-side script. Javascript cannot actively read variables from server. But from a page loads, PHP can pass variables to Javascript by writing to the page the Javascript is on.
Example:
That is the simple way of passing value from php to javascript. And that example will be very useful on passing values from sql to php to javascript. Let's say that we have a database called portfolio, with a table cycler has column of path and title. We can use code like this:
Example:
Code: |
---|
<?php $name = "Melanie"; ?> <script language="javascript" type="text/javascript"> var name = "<?php echo $name; ?>"; document.write(name); </script> |
Output: |
Melanie |
That is the simple way of passing value from php to javascript. And that example will be very useful on passing values from sql to php to javascript. Let's say that we have a database called portfolio, with a table cycler has column of path and title. We can use code like this:
Code: |
---|
<?php //Connecting to database $connection = mysql_connect('localhost, 'password', 'username'); $sql = mysql_select_db('portfolio', $connection); //Getting table in database portfolio $select = "Select * from cycler"; $result = mysql_query( $select ); $row = mysql_fetch_assoc( $result ); //Assigning variables $path = $row['path']; $title = $row['title']; ?> <script language="javascript" type="text/content"> //Assigning variables of php to javascript var path = "<?php echo $path; ?>"; var title = "<?php echo $title; ?>"; //Printing the values document.write("The path of the image is " + path); document.write("The title of the image is " + title); </script> |
Output: |
The path of the image is ./uploads/cycler/portfolio.jpg The title of the image is Melanie's Portfolio |
Remember: That PHP cannot modify external .js documents temporarily. It changes them for good.
Comments
Post a Comment