March 2, 2012
export variable in JavaScript
Question by Flo
Possible Duplicate:
Access a JavaScript variable from PHP
I have one JS code that return my geolocation (latitude, longitude) and I would like to reuse these information in a PHP code. My webpage has .php extention and I have set global variable but it doesn’t work.
How can I do that ?
<script type="text/javascript">
function getCoordPosition(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
});
}
}
</script>
<?php
echo 'Latitude is $latitude';
?>
Answer by Starx
One of the methods are from $_GET method
var test1 = "myvalue";
var link = "thispage.php";
window.location = link+"?test1="+test1;
Then read the value from the testpage.php
Another methods is $.get, or $.post request to a php page.
$.post("mypage.php", {
myvar : "myvalue",
"myanothervar" : "myanothervalue"
}, function(data) {
//data contains the output from the script
});