0

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,515
  • 12
  • 60
  • 89
Sriram
  • 9,924
  • 20
  • 79
  • 136

1 Answers1

3

Try-

res = "<?php echo json_encode($res); ?>";
Sahil Mittal
  • 20,515
  • 12
  • 60
  • 89