To pass JavaScript variables into 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 side, use JavaScript to get the location data (latitude and longitude).
Fetch the city data using an external API like https://api.bigdatacloud.net.
Once you have the city data, make an AJAX POST request to a PHP script on the server.
In the PHP script, access the location data from the $_POST superglobal and insert it into the MySQL database using PDO or MySQLi.
Here's a concise code example:
async function getPosition(position) {
try {
const { latitude, longitude } = position.coords;
const geoApiUrl = `https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${latitude}&longitude=${longitude}`;
const geoResponse = await fetch(geoApiUrl);
const geoData = await geoResponse.json();
const city = geoData.city;
const postData = {
latitude,
longitude,
city
};
const phpUrl = 'insert_location.php';
const response = await fetch(phpUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
});
const result = await response.text();
console.log(result);
} catch (error) {
console.error('An error occurred:', error);
}
}
navigator.geolocation.getCurrentPosition(getPosition);
PHP (insert_location.php):
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$postData = json_decode(file_get_contents('php://input'), true);
$latitude = $postData['latitude'];
$longitude = $postData['longitude'];
$city = $postData['city'];
$pdo = new PDO("mysql:host=your_mysql_host;dbname=your_mysql_database", 'your_mysql_username', 'your_mysql_password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("INSERT INTO location_data (latitude, longitude, city) VALUES (?, ?, ?)");
$stmt->execute([$latitude, $longitude, $city]);
echo 'Location data inserted successfully.';
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
?>