By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,260 Members | 1,677 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,260 IT Pros & Developers. It's quick & easy.

Can I use a php variable in a javascript function?

100+
P: 108
I want to use a php variable in my javascript.
Expand|Select|Wrap|Line Numbers
  1. <script type='text/javascript'>
  2. function display_alert(x){
  3. alert(x);
  4. }
  5. </script>
  6. <body>
  7. <?php $var1='phpvariable';
  8.  
  9. echo "<button onclick='display_alert($var1)'>Diaplay alert</button>";
  10. ?>
  11. </body>
I am not able to execute such a script..
I need to pass a php variable to a javascript function .Is that possible ?
If so,hw cn i implement this?
Thanks in adv
With regards
phpuser123
Apr 13 '10 #1

✓ answered by chathura86

Expand|Select|Wrap|Line Numbers
  1. <script type='text/javascript'>
  2. function display_alert(x)
  3. {
  4.     alert(x);
  5. }
  6. </script>
  7. <body>
  8. <?php 
  9.  
  10. $var1='phpvariable';
  11. $var2='display_alert("' . $var1 . '")';
  12.  
  13. echo "<button onclick=$var2>Display alert</button>";
  14. ?>
  15. </body>
try this

Regards

Share this Question
Share on Google+
4 Replies


Dormilich
Expert Mod 5K+
P: 8,639
you need to pass the variable as JavaScript string, that is, surrounded by " (or ')
Apr 13 '10 #2

100+
P: 108
I passed the variable within quotes as u mentioned..I got $var1 instead of phpvariable ...

Expand|Select|Wrap|Line Numbers
  1. <script type='text/javascript'>
  2.    function display_alert(x){
  3.   alert(x);
  4.   }
  5.   </script>
  6.   <body>
  7.   <?php $var1='phpvariable';
  8.  $var2='display_alert("$var1")';
  9.  
  10.  echo "<button onclick=$var2>Display alert</button>";
  11.  ?>
  12.  </body>
Is that what u exactly u mean ?
To some extent it worked bt I gt the name of my variable instead of the value it holds..
Apr 15 '10 #3

chathura86
100+
P: 227
Expand|Select|Wrap|Line Numbers
  1. <script type='text/javascript'>
  2. function display_alert(x)
  3. {
  4.     alert(x);
  5. }
  6. </script>
  7. <body>
  8. <?php 
  9.  
  10. $var1='phpvariable';
  11. $var2='display_alert("' . $var1 . '")';
  12.  
  13. echo "<button onclick=$var2>Display alert</button>";
  14. ?>
  15. </body>
try this

Regards
Apr 15 '10 #4

100+
P: 108
@chathura86
Thanks that worked out..
Apr 16 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.