Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
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 5 at 4:23
    

4 Answers 4

up vote 8 down vote accepted

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; ?>;  
share|improve this answer
    
If you know for a fact that it's an integer then don't surround it by quotes. –  Mikhail Apr 5 at 4:19
    
@Jenz - its not working. When I surround it with quotes, alert(i) shows whole <?php echo $i; ?>; –  user1556433 Apr 5 at 4: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 <?php at the very top? –  user2864740 Apr 5 at 4:31
    
@user2864740 - its running. –  user1556433 Apr 5 at 4:32
    
@nkp No, it's not. You say that "<?php echo $i; ?>" 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 <?php at the very top [of the HTML]?" –  user2864740 Apr 5 at 4:32

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);
}
share|improve this answer

reference!

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

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

alert(abc);
share|improve this answer

Try this window.myVar = ;

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>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.