Any communication between Javascript code and PHP code needs to be instigated by the Javascript. This is because Javascript is a client side script and PHP is server side. The server can't force data to the browser; it can only reply to requests.
The technique of using Javascript on the client side to talk to server side scripts is referred to as AJAX (Asynchronous Javascript And XML). There are several libraries available for simplifying it's usage, and many online tutorials.
Chat with our AI personalities