Luigi
Luigi

Reputation: 75

Need to pass the value of the variable php to javascript but I can not

I need to pass the value of the variable php to javascript but I can not. Try many forms and does not work. work with the following versions and not whether the cause of the failure. Apache 2.2.25 and PHP 5.2.17 (I need to work For Now With These Versions). The value that should receive the variable in the example is "kml/Aechmea_magdalenae.kml"

$anio = $row['kml_map']; 
        <script>

            function initialize() {
              var mexico = new google.maps.LatLng(20.6568241,-103.3984801);
              var mapOptions = {
                zoom: 11,
                mapTypeId: google.maps.MapTypeId.TERRAIN,
                center: mexico
              }

              var url2 = <?php echo json_encode($anio) ?>;
              var url1 = 'http://www.cnf.gob.mx:8090/snif/especies_forestales/';
              var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);     
              var ctaLayer = new google.maps.KmlLayer({url: url1+url2});
              ctaLayer.setMap(map);}

            google.maps.event.addDomListener(window, 'load', initialize);
        </script>

Upvotes: 1

Views: 90

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

As you can see here, echoing a json_encoded url string will escape the forward slashes in that url.
The solution then is either to do:

var url = '<?php echo $anio; ?>';

Making sure that the value of $anio does not contain any single quotes, or (if you're running PHP 5.4 or up), to use this:

var url = <?php echo json_encode($anio, JSON_UNESCAPED_SLASHES); ?>;

Note the lack of quotes (json_encode will add quotes for you), and the use of the JSON_UNESCAPED_SLASHES constant. check the manual for more constants

demo/PoC here

Upvotes: 1

Look this line:

var url2 = <?php echo json_encode($anio) ?>;

If you intend to json_encode (i think is the other way), you should use quotes, some like

var url2 = "<?php echo json_encode($anio) ?>";

Upvotes: 0

Related Questions