So I'm wondering if there is a way to pass Javascript variables into PHP. I'm making a script that gets a location from a website and inserts this location into MySQL to get some analytics data.
This is my Javascript function:
function getPosition(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; const geoApiUrl = 'https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${latitude}&longitude=${longitude}'; fetch(geoApiUrl) .then(res => res.json()) .then(data => { position = data.city console.log(position) }) }
I want to pass position
into PHP. This function is called when the page loads.
I tried using express but it doesn't work for me.
To pass JavaScript variables to PHP and insert them into a MySQL database, you can use AJAX to send the data to a PHP script on the server.
On the client, use JavaScript to get location data (latitude and longitude). Use external API (such as https://api.bigdatacloud.net) to obtain city data. After obtaining the city data, make an AJAX POST request to the PHP script on the server. In a PHP script, access the location data from the $_POST superglobal variable and insert it into a MySQL database using PDO or MySQLi. Here is a concise code example:
PHP (insert_location.php):