I know that this question is asked many times, but they do not have the right solution. I am using ajax to get a response from a PHP Page. Having received the answer, I want to use the value in a PHP variable. Below the code gets the result, but I am confused with its use.
below is my index.php
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function geoSuccess(position) {
var glat = position.coords.latitude;
var glng = position.coords.longitude;
geocoding(glat,glng);
}
function geoError() {
alert("Geocoder failed.");
}
function geocoding(glat,glng){
$.ajax({
type:'POST',
url:'geolocation.php',
data:'latitude='+glat+'&longitude='+glng,
success:function(result){
if(result){
$("#locationg").val(result);
$("#htmllocation").html(result);
}
}
});
}
geolocation.php
<?php
session_start();
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
$json = @file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK"){
$location = $data->results[0]->formatted_address;
for($j=0;$j<count($data->results[0]->address_components);$j++){
$cn=array($data->results[0]->address_components[$j]->types[0]);
if(in_array("locality", $cn))
{
$city= $data->results[0]->address_components[$j]->long_name;
}
}
}else{
echo 'No Location';
}
echo $city;
}
?>
index.php
<?php
$city='<span id="htmllocation"></span>';
?>
when I echo $cityI get the name of the city, but in the control elements it is shown as
<span id="htmllocation">Visakhapatnam</span>
the problem is that I cannot use this in MYSQL because it is in html format and I just want to get only the name of the city, nothing more.
I hope my problem will be clear, please leave a comment if not clear.
source
share