Consider this simple example;
<?php $text = test; ?>
<script type="text/javascript" defer="defer">
var test;
test = "<?php echo $text; ?>"
$(document).ready(function(){
alert(test);
});
</script>
This works fine. Creating the alert with the text from the php var. However, if I place;
<?php $text = test; ?>
below the script - it does not work. I've tried the defer function. What am I doing wrong?
Cheers
3 Answers 3
If you place
<?php $text = "test"; ?>
below the JS code, the the variable $text is not defined yet, so you cannot echo it earlier (edit) in the script.
6 Comments
$text isn't defined? That code defines it! (Well, it tries to do so, but since assigning test will error (unless you've defined a constant called test or something), it breaks). Actually, in retrospect, the whole question doesn't make a lot of sense as it claims things work even though they should error.test, then PHP interprets it as string 'test'. That's why it works if this line is put before <?php echo $text; ?> but obviously it would not echo anything if it was put after it (this is what the OP tried). It is only unclear what the OP really wants to do (your answer also makes sense, given the ambiguity of test). In any way, the downvote is unjustified (whoever did this).Seems like you are trying to assign a client-side variable to a server-side variable?
Due to my knowledge, server-side variables can NOT "interact" directly with client-sider variables without anything in between. This means <?php $test = test; ?> doesn't work properly since variables that are included in <?php ?> will be treated as server-side variables, and thus, your client-side variable test is either considered as
- an undefined constant, or
- a string without quotes
''
Comments
There are two computers involved, the web server (which processes php) and the user's browser (which processes javascript). So no, you cannot transfer a javascript variable back to php without sending the value of that variable from the user's browser to the web server (normally done by posting a form or ajax).
testin PHP?<?php $text = test; ?>is wrong in any case unless you have a constanttest. You should set a proper string:<?php $text = 'test'; ?>. If you think you are referring to the JavaScript variabletestif you put the line at the end, then you are wrong. See @Quentin's answer in this case.