Here in the following example we will capture Latitude & Longitude of your current location using Javascript and display them in input field of HTML form using AJAX without addition page submissions.
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function getLocation() {
var var_latt;
var var_long;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else { /*SHOW ERROR MSG HERE*/ }
}
function showPosition(position) {
var_latt = position.coords.latitude;
var_long = position.coords.longitude;
$.ajax({
//url: 'response.php',
type: 'GET',
data: { var_PHP_data1: var_latt, var_PHP_data2: var_long },
success: function(data) {
//$('#result').html(data);
document.getElementById("latValue").value = var_latt;
document.getElementById("longValue").value = var_long;
}
});
}
</script>
</head>
<body>
<button onclick="getLocation()">Try It</button>
<form method="post">
<input type="text" name="textMe1" id="latValue" />
<input type="text" name="textMe2" id="longValue" />
</form>
</body>
</html>
Also we can send this form data to another php page such as response.php (COMMENTED IN THE ABOVE CODE) to store them in PHP variables as given under.
<?php
$test1 = $_GET['var_PHP_data1'];
$test2 = $_GET['var_PHP_data2'];
echo "variable is : ".$test1." & ".$test2;
?>
To get the above data, you can create a div with id 'result' and uncomment the following code from the above.
//$('#result').html(data);
Thank You
Happy Coding....
ConversionConversion EmoticonEmoticon