Search code examples
phpsessionjavaagents

$_SESSION not passing to javascript


This is probably a simple issue but I would appreciate any help
I have loaded a $_SESSION variable from my MVC model , its a multidimensional area of latitude and longitude points in a map. here where I loaded this from

         for($i=0; $i<count($markets['results']); $i++) {
        .
        .
     $marketinfo["lat"][$i] = floatval($lat);
             $marketinfo["long"][$i] = floatval($lon);
             };
          $_SESSION['MARKETLOCATION']['LAT'] = $marketinfo["lat"];
          $_SESSION['MARKETLOCATION']['LONG'] = $marketinfo["long"];  

Then down in the view section I am calling a _template for header with this code

<script type="text/javascript"> 
            function createmap(LatLong) {
            var firstpass = true;
            for (var i = 0; i < $LatLong.length; i++) {
                   var  lat = $LatLong['LAT'][i];
                   var  lng = $LatLong['LONG'][i];
                    if (firstpass === true){
                            var map = new google.maps.Map(document.getElementById('map-canvas'),{
                                zoom: 10,
                                center: new google.maps.LatLng($lat[0]+','+$lng[0]),
                                mapTypeId: google.maps.MapTypeId.ROADMAP
                            });
                            firstpass = false;
                    }
                    var infowindow = new google.maps.InfoWindow();
                    marker = new google.maps.Marker({
                        position: new google.maps.LatLng($lat[i]+','+$lng[i]),
                        map: map
                    });

                    }
            window.onload=function(){("createmap($_SESSION['MARKETLOCATION']");};
            }
        </script>
    </head>
    <body>
        <div class='Mapbox' id = 'map-canvas' ></div>

Problem is the map is not displaying at all. I know that my API key is correct because I tested it before I created this code. So I think it probibaly has to do with Passing the session variable Again any insight would be appreciated


Solution

  • Javascript and php are two different languages. You need to output your variable from php but you cannot just echo it as $_SESSION['MARKETLOCATION'] is an array.

    You should do something like:

    var session_variable = <?php echo json_encode($_SESSION['MARKETLOCATION']); ?>;
    // now you might have to do some processing on session_variable like parsing it...
    // for an example:
    var session_object = JSON.parse(session_variable);
    window.onload=function(){ createmap(session_object); };