Getting php variables into javascript

This section is for posting questions which are not directly related to WYSIWYG Web Builder.
Examples of off topics: web server configuration, hosting, programming related questions, third party scripts.

Note that these questions will generally not be answered by the administrators of this forum.
Post Reply
User avatar
alex4orly
 
 
Posts: 632
Joined: Mon Jan 20, 2014 8:17 am
Location: Australia
Contact:

Getting php variables into javascript

Post 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>
mnwitten
 
 
Posts: 37
Joined: Sun Aug 17, 2008 10:29 am
Location: Newfoundland, PA
Contact:

Re: Getting php variables into javascript

Post 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
User avatar
Navaldesign
 
 
Posts: 862
Joined: Sat Mar 01, 2008 8:08 pm
Location: Italy
Contact:

Re: Getting php variables into javascript

Post 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.
www.dbtechnosystems.com
User avatar
alex4orly
 
 
Posts: 632
Joined: Mon Jan 20, 2014 8:17 am
Location: Australia
Contact:

Re: Getting php variables into javascript

Post 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
Post Reply