-2

I don't have much programming experience.
I have some code that I'm adapting and I don't understand how the variables are being passed from PHP to JavaScript. I suspect I'm missing out on a bit of basic theory but I have so far been unable to track it down on the web. Google maps marker information is being passed as follows: -

<?php  
$mrk_cnt = 0;    
while ($obj = $res->fetch_object()){
    $username[$mrk_cnt] = $obj->username;
    $inf[$mrk_cnt] = $obj->title;   
    $lat[$mrk_cnt] = $obj->lat;
    $lng[$mrk_cnt] = $obj->long;
    $begin[$mrk_cnt] = $obj->begin;
    $end[$mrk_cnt] = $obj->end;
    $distance[$mrk_cnt] = $obj->distance;
    $marker_type[$mrk_cnt] = $obj->type;
    $icon[$mrk_cnt]=(($marker_type[$mrk_cnt]=='inquirer')? 'red_marker': 'blue_marker');    
$mrk_cnt++;    
}
?>

Further on there's some JavaScript echoed from php: -

<script>
<?php
    for ($lcnt = 0; $lcnt < $mrk_cnt; $lcnt++){ 
        echo "var point$lcnt = new google.maps.LatLng($lat[$lcnt], $lng[$lcnt]);\n";
        echo "var mrktx$lcnt = \"$inf[$lcnt]\";\n";
        echo "var infowindow$lcnt = new google.maps.InfoWindow({ content: mrktx$lcnt });";
        echo "var marker$lcnt = new google.maps.Marker({position: point$lcnt, map: map, icon:" . $icon[$lcnt] . "});\n";
        echo "google.maps.event.addListener(marker$lcnt,'click', function() {infowindow$lcnt.open(map,marker$lcnt);});\n";
        echo "bounds.extend(point$lcnt);\n";    
    }
?>
    map.fitBounds(bounds);
}
</script>

How are the php variables - $lat[], for instance - finding their way into the JavaScript? They are declared in PHP and they are not being concatenated or quoted. It is assumed the JavaScript will know that $lat[$lcnt] will be the $lat[$mkr_cnt] declared in the php above with $lcnt set to =$mkr_cnt.
Many thanks.

user2790911
  • 175
  • 1
  • 4
  • 12

1 Answers1

0

The second block of code you gave literally does that, echoes the javascript to your page, javascript is not concerned if it comes from PHP or any other language, by echoing html/javascript code in your script in this case, you are giving information for the javascript that will run under that page, PHP worked only to retrieve the data from the API and then mounted the javascript that will make it work in browser.

Another handy information about single/double quotes in PHP: What is the difference between single-quoted and double-quoted strings in PHP?

Community
  • 1
  • 1
G.Mendes
  • 1,201
  • 1
  • 13
  • 18
  • Thanks, that is the vital bit of information I was missing. I found this page set it out most clearly for me: http://hydrogen.informatik.tu-cottbus.de/wiki/index.php/PHP_Variable_Interpolation – user2790911 Nov 26 '13 at 13:54