Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access PHP variable in JavaScript code?

I have a variable in PHP code which I want to access in my JavaScript function. Below is my code.

myfile.php

<?php
  $i = 0;
?>
<html>
  <head>
    <script type="text/javascript">
      function SetText() {
        //I want to access value of i here
        //alert(i);
      }
    </script>
  </head>
  <body>
    <button type="button" id="mybutton" onclick="SetText()">Click ME</button>
  </body>
</html>

What are the ways to access I variable declared in php code in the JavaScript code?


2 Answers

You can access a PHP variable inside javascript by echoing it within quotes if the value is a string and just need to echo if it is an integer, like;

var i=<?php echo $i; ?>;  
like image 87
Jenz Avatar answered Dec 04 '25 21:12

Jenz


SetTextUse this

<button type="button" id="mybutton" onclick="SetText(<?php echo $i; ?>)">Click ME</button>    

And in Javascript use this

function SetText(id)
{
alert(id);
}
like image 23
Professor Avatar answered Dec 04 '25 21:12

Professor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!