Skip to content Skip to sidebar Skip to footer

Php Is Finish Loaded Then Only Start Load Javascript. Is It True?

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 javascr

Solution 1:

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:

<scripttype="text/javascript">
alert("<?phpecho$username; ?>");
</script><?php$username = "abc"; ?>

To, on the client:

<scripttype="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"; ?><scripttype="text/javascript">
alert("<?phpecho$username; ?>");
</script>

Which allows php to evaluate/assign the variable, and then have the variable set/available in the alert() statement.

Solution 2:

PHP is run on the server BEFORE any of the javascript is parsed. You need to assign your variable before it used. That's the problem above.

Solution 3:

PHP does not load or execute Javascript. Here is an order of execution:

  1. The user requests data from your web server.
  2. Your web server executes your PHP script, which outputs some HTML/Javascript.
  3. The web server sends the HTML/Javascript to the user's browser.
  4. The user's browser renders the HTML and executes the Javascript.

So yes, the PHP will finish executing before the Javascript is executed.

Solution 4:

I heard people said php codes will be finished loaded then only will start loading javascript.

This is absolutely true, your server scripts will be run first.

The reason it doesn't alert() anything is because $username does not even exist yet...

Once the PHP script runs it is done, unless you call more from AJAX.

Solution 5:

PHP is run at the web server. It parses the file and returns HTML like this:

<scripttype="text/javascript">alert("");
</script>

When it has arrived at the client side, no variables are being set anymore as you can see.

Post a Comment for "Php Is Finish Loaded Then Only Start Load Javascript. Is It True?"