Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php is finish loaded then only start load javascript. Is it true? [duplicate]

Tags:

javascript

php

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?

like image 933
zac1987 Avatar asked Dec 01 '22 08:12

zac1987


1 Answers

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.

like image 81
David Thomas Avatar answered Dec 06 '22 15:12

David Thomas