Generally you do it either via Page submit (GET/POST) or via a XMLHttpRequest (async call).
There are more ways like Callback, Cookies, Session, etc too based on what makes more sense for you.
An example via page GET/POST & via Cookies:
How to pass JavaScript variables to PHP ? - GeeksforGeeks[
^]
An example on XMLHttpRequest:
AJAX PHP[
^]
An example with more ways:
https://link.springer.com/content/pdf/bbm:978-1-4842-4463-0/1.pdf[
^]
Try out and see which works for you more.