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?

vectorijk
  • 364
  • 3
  • 10

3 Answers3

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>
11684
  • 7,356
  • 12
  • 48
  • 71
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

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
  • That is a too big subject to explain in a comment, but I'd suggest to pick a tutorial from here: http://www.smashingmagazine.com/2008/10/16/50-excellent-ajax-tutorials/ @Tonyjiang – 11684 Feb 20 '13 at 16:55
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.

Eng. M
  • 48
  • 5
  • It is, see the two other answers. – 11684 Feb 19 '13 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) – Eng. M Feb 19 '13 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. – 11684 Feb 19 '13 at 13:35