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,697
  • 12
  • 65
  • 90
Sriram
  • 10,298
  • 21
  • 83
  • 136

1 Answers1

3

Try-

res = "<?php echo json_encode($res); ?>";
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90