Reputation: 879
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
Upvotes: 1
Views: 276
Reputation: 22246
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).
Upvotes: 0
Reputation:
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
''
Upvotes: 1
Reputation: 7465
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.
Upvotes: 6