If you want to set the variable when the page loads, you could use something like this in the PHP code:
Just make sure to remove the later variable declaration from the JavaScript.
If you want to set the variable after the page loads, you'll have to use an AJAX call to ge the value from the server.