2

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?

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • 1
    You can *emit* the corresponding JavaScript from PHP for the task. I recommend using json_encode for consistency - it will correctly deal with primitives as the "root object". – user2864740 Apr 05 '14 at 04:23
  • possible duplicate of [Pass a PHP string to a JavaScript variable (and escape newlines)](http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-and-escape-newlines) – Fazal Rasel Apr 05 '14 at 08:01

4 Answers4

11

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; ?>;  
Jenz
  • 8,280
  • 7
  • 44
  • 77
  • If you know for a fact that it's an integer then don't surround it by quotes. – Mikhail Apr 05 '14 at 04:19
  • @Jenz - its not working. When I surround it with quotes, alert(i) shows whole ; –  Apr 05 '14 at 04:30
  • @nkp Sounds like your PHP isn't even running. Right-click on the HTML page in the browser and go to "View source". Do you see ` – user2864740 Apr 05 '14 at 04:31
  • @user2864740 - its running. –  Apr 05 '14 at 04:32
  • @nkp No, it's not. You say that "" was alerted. Given the posted code in this answer and the context of the question, this will only happen if the PHP file is not being processed correctly. So, again, "Do you see – user2864740 Apr 05 '14 at 04:32
  • @nkp..this is tested and is working fine..check whether there is any other issues.. – Jenz Apr 05 '14 at 04:37
1

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);
}
Professor
  • 610
  • 4
  • 20
1

reference!

i am using this code for access it's working you can try it

var abc = <? php echo $a; ?>

alert(abc);
The Boss
  • 11
  • 1
1

Try this

<script>
      window.myVar = <?php echo $i; ?>;
</script>

or put all your variables (which you wanna paas to ui/js) into some array

and define this function

function sendToJS($array){
     for (var $i in $array){
       echo  'window.'.$i.'="'.$array.'";' 
     }
}

then in your html/php file

<script><?php 
    sendToJS($myVars);
?></script>
Ram Sharma
  • 8,676
  • 7
  • 43
  • 56
Amit
  • 1,841
  • 1
  • 19
  • 36