Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
4  
enclose it in quotes.. res = '<?php echo json_encode($res); ?>'; –  Shankar Damodaran Mar 25 at 12:12
add comment

2 Answers

Try-

res = "<?php echo json_encode($res); ?>";
share|improve this answer
    
That does not work. If I do console.log(res); after the above statement, res is output as "<?php echo json_encode($res); ?>". –  Sriram Mar 25 at 12:22
    
You file must be a .php. Is it? –  Sahil Mittal Mar 25 at 12:27
    
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? –  Sriram Mar 25 at 12:30
    
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! –  Sahil Mittal Mar 25 at 12:32
add comment

You can't, you'll have to do something like

<script type="text/javascript">
   var php_var = "<?php echo $php_var; ?>";
</script>

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.