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:
To, on the client:
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:
Which allows php to evaluate/assign the variable, and then have the variable set/available in the alert() statement.