-2

so I would like to now if is there any way to pass Javascript variable into PHP. I'm making a script to get location from website and I want to insert this location into MySQL to get some analytic data.

Here 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)
  })
}

and I want to pass position into PHP. This function is called on page load.

I tried using express but it wasn't working for me.

1
  • 1
    Make another fetch request. Commented Aug 3, 2023 at 10:50

1 Answer 1

-1

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();
  }
}
?>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.