Possible Duplicate:
How to ask javascript wait for mysql assign value to php variable?
I heard people said php codes will be finished loaded then only will start loading javascript. Info at How to ask javascript wait for mysql assign value to php variable?
But When I wrote :
<script type="text/javascript">
alert("<?php echo $username; ?>");
</script>
<?php $username = "abc"; ?>
It fail to alert the value of php variable. It is because javascript is loaded at first, then only start loading php. So the fact of server-site script is finish loaded then only start load client-site script is wrong?
If javascript can be executed before php, then I have problem to ask javascript wait for mysql assign value to php variable. Please help me to solve this problem at How to ask javascript wait for mysql assign value to php variable?
PHP is executed on the web-server, generating an html (or whatever) page to be displayed by the browser. JavaScript is executed on the client-side, in the user's browser, therefore php has, by definition, finished executing before JavaScript executes.
You seem to be assuming that php runs, then JavaScript is run, in the same place. Which is a fallacy; the problem you're having is that you assign the JavaScript variable to the value of the $username
variable before the php script has assigned/evaluated the variable; which should transform, on the server, from:
<script type="text/javascript">
alert("<?php echo $username; ?>");
</script>
<?php $username = "abc"; ?>
To, on the client:
<script type="text/javascript">
alert("");
</script>
Therefore, while your script appears to do nothing, or do the wrong thing, it's doing exactly what you told it to do. You should try and rearrange your code a little to:
<?php $username = "abc"; ?>
<script type="text/javascript">
alert("<?php echo $username; ?>");
</script>
Which allows php to evaluate/assign the variable, and then have the variable set/available in the alert()
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With