First, you need to understand that php and javascript work on different computers.
Php runs on the server, while javascript runs on the client computer. This makes things a little undifferentiated. I mean, php and javascript cannot directly modify variables because they do not run at the same time. The first php runs on the server, prepares HTML and js and passes it to the client, and then on the computer javascript runs on the computer, if javascript needs something from the server, it calls the server again (either post, get, or ajax does not matter, this is still an http request).
So, from php to javascript you can pass a variable when preparing javascript, in which pont only runs php and no javascript, and from javascript to php you can pass a variable by making a request from the client computer to your php server with some variables.
source share