Search code examples
javascriptphpgeojson

How can I define variable in javascript using PHP


I am developing an application and I would like to define a javascript variable using PHP code. In a database I have in 3 points from the type batiment and I would that the variable geojson point had 3 value (I would that the variable var geojson_Point have all the result of the request in the geometry "geometry" : echo $rslt;").

var geojson_Point = 
{
    <?php 
    $query = "SELECT ST_ASGeoJSON(geometry) FROM poi where type='batiment'";  
    $result = pg_query($con, $query);
    while ($row = pg_fetch_assoc($result))  
    {  
        foreach($row as $rslt);
            "type": "Feature",
            "properties": { },
            "geometry":
        echo $rslt; 
    } 
    ?>;
}

Solution

  • To define javascript variable from PHP use :

    var JS_variable = <?php echo $PHP_variable; ?>;
    

    In your case a suggest to separate php & javascript codes like following :

    PHP :

    $result_array = array();
    
    while ($row = pg_fetch_assoc($result))  
    {  
        foreach($row as $rslt){
            $geojson_point = array("type" => "Feature", "properties" => "{}", "geometry" => $rslt);
    
            array_push($result_array, $geojson_point);
        }
    }
    

    Pass the variable to javascript like following :

    JS :

    var geojson_point = <?php echo json_encode($result_array); ?>;
    

    Hope this helps.