-1

how do I use PHP with Javascript? I am trying to make PHP session vars to be equals to the geolocation values from JS. Is this possible?

PHP

$_SESSION['latitude'] = ?
$_SESSION['longitude'] = ?

Geolocation Function in Javascript:

function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{ 
document.getElementById('showlat').innerHTML = position.coords.latitude; 
document.getElementById('showlong').innerHTML = position.coords.longitude;
}
user2192094
  • 337
  • 2
  • 6
  • 15
  • You can't set values in PHP from JavaScript. I think you need to understand what code is processed where. PHP is processed on the server and then delivers the page, where your javascript can be processed by the browser, so you can see that it can't go back the other way without refreshing the page or moving to another page. – jdcookie Feb 20 '14 at 15:51
  • As if stuff similar to this hasn’t been asked a thousand times already … – CBroe Feb 20 '14 at 16:17

3 Answers3

1

You can use JavaScript to make an asynchronous request to a script on your server, which in turn sets the PHP session variable. Orther than this, I don't think there's any other way.

0

In JavaScript you can make a HTTPXMLRequest to 'post' data from your JavaScript to PHP. An easier way to do it is to use JQuery to call the $.ajax method which is laid out a bit better than the old fashioned HTTPXMLRequest. Make a JavaScript variable to store the geo data and send it via ajax as JSON data. PHP will receive this data via POST or GET and can use it the same way it receives form data from HTML.

JS Ex)

var lat = 'what ever the latitude is';
var longi = 'what ever the longitude is';

$.ajax(
{
     url:'what ever your php page is',
     type:'post',
     data:{latitude:lat,longitude:longi},
     success:function(data)
     {
          console.log(data+' was sent successfully');
     },
     error:function()
     {
          console.log('data was NOT sent');
     }
});

PHP Ex)

<?php
session_start();
$_SESSION['longitude']=$_POST['longitude'];
$_SESSION['latitude']=$_POST['latitude'];

?>
13ruce1337
  • 753
  • 1
  • 6
  • 13
0

Make sure your PHP file has session_start(); otherwise the ajax call will not work.