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?
-
1You 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– user28647402014年04月05日 04:23:17 +00:00Commented Apr 5, 2014 at 4:23
-
possible duplicate of Pass a PHP string to a JavaScript variable (and escape newlines)Fazal Rasel– Fazal Rasel2014年04月05日 08:01:01 +00:00Commented Apr 5, 2014 at 8:01
4 Answers 4
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; ?>;
6 Comments
<?php at the very top?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);
}
Comments
i am using this code for access it's working you can try it
var abc = <? php echo $a; ?>
alert(abc);
Comments
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>