My HTML code collects latitude and longitude coordinates and sends them to a PHP script using AJAX. However, the issue is that the AJAX request inserts NULL values into the database table. It seems to be inserting "0.000000" for both Latitude and Longitude fields even though they are defined as float(10,6) in the database following GPS coords best practices. As I am a new developer, any help would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<title>AJAX DATABASE</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
/*/ Wait for Cordova to load
/*/
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// Cordova is ready
//
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = {enableHighAccuracy:true, timeout: 3000, maximumAge:0};
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var latitude = document.getElementById("lat");
latitude.innerHTML = position.coords.latitude;
var longitude = document.getElementById("longitude");
latitude.innerHTML = position.coords.latitude;
insertDB(position.coords.latitude,position.coords.longitude);
}
// onError Callback receives a [PositionError](PositionError/positionError.html) object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Options: throw an error if no update is received every 30 seconds.
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });
// Sends latitude & longitude value to php script and alerts on success
function insertDB(latitude, longitude){
var xttp = new XMLHttpRequest();
xttp.onreadystatechange = function(){
if(this.readyState == 4){
document.getElementById('longitude').innerHTML =
this.responseText;
alert("state changed by ajax")
}
}
xttp.open("GET", "ConnectTest.php?latitude="+latitude+"&longitude="+longitude, true);
xttp.send();
}
</script>
</head>
<body>
<p id="lat"></p><br>
<p id="longitude"></p>
</body>
</html>
The corresponding PHP script:
<?php
//POST VARIABLES
$one = $_GET['latitude'];
$two = $_GET['longitude'];
//ESTABLISH CONNECTION
$servername = "localhost:3306";
$user = "client";
$pass = "sonic_client";
$db_name = "sonicstrains";
$server = mysqli_connect($servername, $user, $pass, $db_name);
$sql = "SELECT * FROM 'users' WHERE 'latitude' = ".$two;
$result = mysqli_query($server, $sql);
if(!isset($_GET['latitude'])){
echo "Nothing is set";
}
if(!$server){
die("Connetion error".mysqli_connect_error());
}else{
if (!$result){
$insert = "INSERT INTO users (latitude, longitude) VALUES ('$one', '$two')";
mysqli_query($server, $insert);
echo "Coordinates Inserted";
}
}
?>