Sriram
Sriram

Reputation: 10558

Using Javascript to access PHP variables

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).

Upvotes: 0

Views: 63

Answers (1)

Sahil Mittal
Sahil Mittal

Reputation: 20753

Try-

res = "<?php echo json_encode($res); ?>";

Upvotes: 3

Related Questions