使用php将结果html文件(包含js代码)导入mysql
I am try to get my location using javascript, but when i click submit data not entered to page action.php
geolocation.php
<form action="action.php" method="post">
<input type="hidden" name="lat" id="geolocation"><br>
<input type="submit" value="Submit">
</form>
<script>
var z = document.getElementById("geolocation");
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) { z.innerHTML = position.coords.latitude + "&lng=" + position.coords.longitude; }
</script>
action.php
<?php
$lat = $_POST['lat'];
$lng = $_POST['lng'];
include 'koneksi.php';
mysqli_query($koneksi,"
INSERT INTO
`data`(lat,lng)
VALUES
('$lat','$lng') ") or die ("ERROR WHEN INSERTING 1 OR DUPLICATE VALIDATE");
?>
When you send form data to PHP with the POST method, it reads each field's value attribute, not its HTML.
You can create two hidden fields and set their value
s in JavaScript, like this:
<form action="location.php" method="post">
<input type="hidden" name="lat" id="latitude"><br>
<input type="hidden" name="lng" id="longitude"><br>
<input type="submit" value="Submit">
</form>
<script>
const latitude = document.getElementById("latitude");
const longitude = document.getElementById("longitude");
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
latitude.value = position.coords.latitude;
longitude.value = position.coords.longitude;
}
</script>
Also be aware that if you don't validate user input, and don't use prepared statements, that you're vulnerable to SQL injections.
Input field values are set via .value
, not .innerHTML
. What you want, is
function showPosition(position) { z.value = …; }
But if you want both values easily accessible via $_POST on the server side, you need to use two input fields to begin with. Right now you are sending both lat and long as one value, so you would have to take it apart on the server side again.