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.7k12 gold badges68 silver badges91 bronze badges
asked Mar 25, 2014 at 12:11
1
  • 4
    enclose it in quotes.. res = '<?php echo json_encode($res); ?>'; Commented Mar 25, 2014 at 12:12

1 Answer 1

3

Try-

res = "<?php echo json_encode($res); ?>";
answered Mar 25, 2014 at 12:13
Sign up to request clarification or add additional context in comments.

4 Comments

That does not work. If I do console.log(res); after the above statement, res is output as "<?php echo json_encode($res); ?>".
You file must be a .php. Is it?
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?
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!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.