Page 1 of 1

Getting php variables into javascript

Posted: Wed Feb 22, 2017 12:32 am
by alex4orly
I am using the Google Map API and am trying to capture URL arguments into the JavaScript for the map.
Here is my URL including the arguments:

http://www.beleuramyhome.org.au/myvilla ... lvilla=177

Here is my actual code (which doesn't work) = the result you see through the above link is hard coded at the moment.
The PHP part of retrieving the URL arguments works fine, but the assignment into the JS variables doesn't work... Why?

<?php
$phplat = "<?php echo $_GET["urllong"]?>";
$phplong = "<?php echo $_GET["urllong"]?>";
$phpvilla = "<?php echo $_GET["urlvilla"]?>";
?>

<script type="text/javascript">

var map;

var mylat = $phplat;
var mylong = $phplong;
var myvilla = $phpvilla;

function initMap()
{
var myLatLng = {lat: mylat, lng: mylong};
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 18,mapTypeId: 'satellite'
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: myvilla
});
}

</script>

<script src="https://maps.googleapis.com/maps/api/js ... ck=initMap"
async defer></script>

Re: Getting php variables into javascript

Posted: Wed Mar 22, 2017 3:25 pm
by mnwitten
This is my understanding of how this works:

Your HTML page before processed by PHP=======
<PHP
echo 'var myVar = 100';
?>

alert(myVar); // should alert 100

Your HTML page after processed by PHP=====
The following will be echoed by PHP into your HTML page

var myVar = 100;

alert(myVar); // should alert 100

Re: Getting php variables into javascript

Posted: Thu Mar 23, 2017 5:51 am
by Navaldesign
You simply need to use the following in the Javascript code:

var mylat = <?php echo $_GET["urllat"];?>
var mylong = <?php echo $_GET["urllong"];?>
var myvilla = <?php echo $_GET["urlvilla"];?>

Do NOT use the part

<?php
$phplat = "<?php echo $_GET["urllong"]?>";
$phplong = "<?php echo $_GET["urllong"]?>";
$phpvilla = "<?php echo $_GET["urlvilla"]?>";
?>

It is useless and also contains syntax errors.

Re: Getting php variables into javascript

Posted: Thu Mar 23, 2017 8:10 am
by alex4orly
Thanks guys for the help,

I have sorted it out in the meantime, reading the long/lat from a csv file and passing that into the function

Cheers