In my php page I am storing users city when he comes to my site.
Here is google API I got from web.
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAp04yNttlQq-7b4aZI_jL5hQYPm-xtd00hTQOC0OXpAMO40FHAxQMnH50uBbWoKVHwgpklyirDEregg"></script>
<script type="text/javascript">
if(google.loader.ClientLocation)
{
visitor_lat = google.loader.ClientLocation.latitude;
visitor_lon = google.loader.ClientLocation.longitude;
visitor_city = google.loader.ClientLocation.address.city;
visitor_region = google.loader.ClientLocation.address.region;
visitor_country = google.loader.ClientLocation.address.country;
visitor_countrycode = google.loader.ClientLocation.address.country_code;
document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
}
else
{
document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
}
</script>
I need store it as a PHP variable. Can some one tell me how I can use it in a php page?
I know traditional way to echo
all <html> to </html>
and put above code inside it. But want to know any other better way?
I also don't know how to assign a javascript variable to a php value.
also dont know how to asign javascript var value to php value.
You can't do that because Javascript runs in the client, the browser and php on the server.
You can also easily get visitor's location details from IP address in php:
<?php
require_once("userip/ip.codehelper.io.php");
require_once("userip/php_fast_cache.php");
$_ip = new ip_codehelper();
$real_client_ip_address = $_ip->getRealIP();
$visitor_location = $_ip->getLocation($real_client_ip_address);
$guest_ip = $visitor_location['IP'];
$guest_country = $visitor_location['CountryName'];
$guest_city = $visitor_location['CityName'];
$guest_state = $visitor_location['RegionName'];
echo "IP Address: ". $guest_ip. "<br/>";
echo "Country: ". $guest_country. "<br/>";
echo "State: ". $guest_state. "<br/>";
echo "City: ". $guest_city. "<br/>";
?>
For details go here http://www.a2zwebhelp.com/visitor-location-in-php
You cannot assign a Javascript variable value to a PHP variable because the Javascript is running on the Client Borwser and the PHP script runs on the Server.
But there is a way of sending it back to the server using POST or GET method..
You can even use AJAX/JQuery to do it.
One of the Method that uses Jquery is the easiest. here is the Link to it : http://api.jquery.com/jQuery.ajax/
Create a PHP File on your server call it storecity.php
<?php
$city = $_GET['city'];
$user = $_GET['name'];
// Write your code to store the variable $city into the database
?>
then add this code after you get the User's City (Note to include Jquery Library for this to work)
$.ajax({
type: "GET",
url: "storecity.php",
data: { name: "John", city: "Boston" }
});