What's wrong is a fundamental mistake. PHP is a server-side language, so all PHP code is executed before the page is ever sent to the user's browser, which is when the Javascript (client-side code) is then executed.
Either use all Javascript, or else look into using AJAX to send the user's response back to your server for processing.