0

How to use javascript to access php variable? Does only one way to write code (like var a={?echo $variable})in javascript?

Recommend some books on php and javascipt(include projects)?I don't know how to use knowledge in projects?

0

3 Answers 3

1

Yes, you were correct.
Because PHP is executed before JavaScript, you can't change it later on, but you could do something like this:

<? $aVar = "whatever"; ?>
...
<script>
    var aVar = "<? echo $aVar; ?>"; // note the quotes! (SO's highlighter renders this incorrectly, starting a PHP block inside quotes is valid and will be recognized.)
</script>

That will send this to the client:

<script>
    var aVar = "whatever"; // note the quotes!
</script>
0
var a=<?php echo $variable; ?>

PHP runs in server and js in client side, so Iguess there is not other you can get it. OR you need to use AJAX

1
0

I don't see how can you do that in any other method. PHP is server side, while JS is executed on client's PC (not on the web server). Theoretically and practically it's not possible.

3
  • It is, see the two other answers. Commented Feb 19, 2013 at 13:27
  • to be accurate, you're not accessing the variable using JS at all. It is impossible for JS to access PHP variable and vice versa. What echo is doing is handing in the value of the variable at the exact moment you ask for it (it might change on the server afterward while you think you have it on the loaded JS code) Commented Feb 19, 2013 at 13:34
  • I am aware of that. But it seems our definitions of 'access' differ. What I mean with 'access' is "get it's value", not "have a pointer to it". And echo effectively gives the value of a variable to JS. Commented Feb 19, 2013 at 13:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.