C0ld
C0ld

Reputation: 123

Get location from JavaScript and pass it to PHP

I want to get the longitude and latitude using javascript, and than to compare it with the previous location. Something like Facebook does when you log in from another computer, but much more simplified. In order to achieve this I have created 2 hidden fields and when the user submits the form the values are to be sent to the server.

<body>
<p id="log">Login to continue:
    <form action="welcome.php" method="post">
        Username: <input type="text" name="user" required >
        Password: <input type="password" required>
    <input type="hidden" name= "longitude" id="longitude">
    <input type= "hidden" name ="latitude" id="latitude">

    <input type="submit" name="submit" onclick="getLocation()">
</p>
<script>
var x=document.getElementById("log");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
     var latitude = position.coords.latitude;
     var longitude = position.coords.longitude;  
     document.getElementByID("longitude").value = longitude;
     document.getElementByID("latitude").value = latitude;

  }

</script>

But in welcome.php the code :

$latitude=$_POST["latitude"];
$longtude=$_POST["longitude"];

returns : Notice: Undefined index: latitude in C:\xampp\htdocs\welcome.php on line 8

Notice: Undefined index: longitude in C:\xampp\htdocs\welcome.php on line 9

Is there better way to do this, and how to fix this?

Upvotes: 2

Views: 2350

Answers (4)

user1433439
user1433439

Reputation:

Open firebug, click on label network and take a look into the post request if parameters langitude and longitude have been sent. If yes, the failure must be in your php script. If you cant't find both parameters, check your client code.

Upvotes: 0

CuriousMind
CuriousMind

Reputation: 34175

Change this

function showPosition(position)
  {
     var latitude = position.coords.latitude;
     var longitude = position.coords.longitude;  
     document.getElementByID("longitude").value = longitude;
     document.getElementByID("latitude").value = latitude;

  }

to this

function showPosition(position)
  {
     var latitude = position.coords.latitude;
     var longitude = position.coords.longitude;  
     document.getElementById("longitude").value = longitude;
     document.getElementById("latitude").value = latitude;

  }

And it should work

Upvotes: 0

sAnS
sAnS

Reputation: 1163

you have made mistake on document.getElementByID the d should be small ie document.getElementById

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

You are trying to access the elements by ID, but they have no ID.

Either add an ID attribute to them, or reference them in a different way.

Upvotes: 4

Related Questions