Pass Jquery variable to PHP

Asked

Viewed 3,070 times

4

I’m with this script that brings user geolocation:

(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 to make:

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

But it didn’t work.

You can pass Jquery values to PHP?

1 answer

4


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

Therefore, you will need a server-side PHP script to receive and handle the coordinates.

To do this with jQuery, an example would be, after picking up 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 it is a simple example that demonstrates the conversation (data exchange) between client (browser) and server (your code in PHP).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.