"Converting JavaScript Variables to PHP: JavasScript variables converted to PHP"
P粉904405941
P粉904405941 2023-09-18 11:50:08
0
1
495

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.

P粉904405941
P粉904405941

reply all(1)
P粉648469285

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:

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 => {
      const city = data.city;

      // 使用AJAX将位置数据发送到PHP
      const xhr = new XMLHttpRequest();
      const phpUrl = 'insert_location.php';
      const params = `latitude=${latitude}&longitude=${longitude}&city=${encodeURIComponent(city)}`;
      xhr.open('POST', phpUrl, true);
      xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      xhr.send(params);
    });
}

PHP (insert_location.php):

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // 从AJAX请求中获取位置数据
  $latitude = $_POST['latitude'];
  $longitude = $_POST['longitude'];
  $city = $_POST['city'];

  // 使用PDO将数据插入到MySQL数据库中
  $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 '位置数据插入成功。';
}
?>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template