Pass Jquery variable to PHP

2

I'm with this script that brings the geolocation of the user:

(function() {

if(!!navigator.geolocation) {

	var map;

	var mapOptions = {

	};
	
	map = new google.maps.Map(document.getElementById('google_canvas'), mapOptions);

	navigator.geolocation.getCurrentPosition(function(position) 
	{		
		var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
		var php_latitude = position.coords.latitude;
		var php_longitude = position.coords.longitude;
		alert(php_latitude);
	});
	
} else {
	document.getElementById('google_canvas').innerHTML = 'No Geolocation Support.';
}

})();
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&key=XXX"></script>

I need to pass latitude and longitude values to variables in PHP.

I tried doing:

<?php 
  $variavelphp = "<script>document.write(php_latitude)</script>";
  echo "Olá $variavelphp";
?>

But it did not work.

Is it possible to pass Jquery values to PHP?

    
asked by anonymous 25.05.2017 / 12:23

1 answer

2

You need to send via Ajax (Javascript call). Understand that by running javascript in the browser you are "disconnected" from the server.

So you will need a PHP script on the server side to receive and handle the coordinates.

To do this with jQuery, an example would be, after getting the coordinates:

$.ajax({
   method: "POST",
   url: "caminho-para-script.php",
   data: { lat: php_latitude, long: php_longitude }
})
  .done(function( msg ) {
       // resposta do servidor
       alert( msg );
});

And a possible PHP script

<?php
    $lat  = $_POST['lat'];
    $long = $_POST['long'];

    // comandos para salvar os dados

    // exemplo de resposta
    echo "Latitude " . $lat . " e Longitude " . $long . " recebidas.";

Note that this is a simple example that demonstrates the conversation (data exchange) between client (browser) and server (your PHP code).

    
25.05.2017 / 13:55