How can I access PHP variables from Javascript where the PHP code exists in a separate file?
The code I have is:
<?php
$res = "OK";
?>
<html>
<head>
<script type="text/javascript">
function myFunc()
{
res = <?php echo json_encode($res); ?>;
console.log("res = " + res);
}
</script>
</head>
<body>
<button onclick="myFunc()">Click</button>
</body>
</html>
Now, if I were to move my php code to a separate file called a.php, how can I access $res? Assume I am calling a.php with a GET request (XMLHttpRequest object).
Sahil Mittal
20.7k12 gold badges68 silver badges91 bronze badges
asked Mar 25, 2014 at 12:11
Sriram
10.6k21 gold badges90 silver badges141 bronze badges
1 Answer 1
Try-
res = "<?php echo json_encode($res); ?>";
answered Mar 25, 2014 at 12:13
Sahil Mittal
20.7k12 gold badges68 silver badges91 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Sriram
That does not work. If I do
console.log(res); after the above statement, res is output as "<?php echo json_encode($res); ?>".Sahil Mittal
You file must be a
.php. Is it?Sriram
After removal of all
php code to a.php, there is nothing left except javascript and html. Does the file still need to be renamed to .php?Sahil Mittal
I'm not sure what are you trying to say; but - if you are using
<?php ?> in a file that file must be a .php file- that's it!default
res = '<?php echo json_encode($res); ?>';