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>
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

That is a too big subject to explain in a comment, but I'd suggest to pick a tutorial from here: smashingmagazine.com/2008/10/16/50-excellent-ajax-tutorials @Tonyjiang
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 Comments

It is, see the two other answers.
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)
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.