class Map
{
public $Id;
public $longitudes;
public $latitudes;
public $lat_init;
public $lng_init;
public static function createMap($Id){
global $latitude, $longitude;
$dbh = Database::connect();
$query = "SELECT * FROM `cartes` WHERE Id=? ";
$sth = $dbh->prepare($query);
$sth->setFetchMode(PDO::FETCH_CLASS, 'Map');
$sth->execute(array($Id));
if ($sth->rowCount() === 0) return NULL;
$map=$sth->fetch();
$sth->closeCursor();
$lat=$map->latitudes;
$lng=$map->longitudes;
$latitude=unserialize($lat);
var_dump($latitude);
$longitude=unserialize($lng);
echo'<script type="text/javascript">'
,'var lat = json_encode($latitude);
var lng = json_encode($longitude);
draw(lat,lng);
'
,'</script>';
}
}
<?php
$dbh=Database::connect();
Map::createMap(6);
?>
When i excute this code, the following error appears: "$latitude is not defined". var_dump($latitude) is ok. I think the script doesn't recognize $latitude but i don't know why. Any help? thanks
-
1Hello! Don't forget to accept an answer, you even get 2 rep for it!SomeKittens– SomeKittens2014年04月04日 21:13:11 +00:00Commented Apr 4, 2014 at 21:13
3 Answers 3
If you're encoding it into JSON, you'll need to wrap it in quotes correctly (you can't call functions inside strings):
echo '<script type="text/javascript">
var lat = '. json_encode($latitude). ';
var lng = '. json_encode($longitude). ';
draw(lat,lng);
</script>';
4 Comments
JSON.parse -- just substitute the result directly into the JS.With PHP, single quote are for string literals and will use the name of the variable instead of its value. If you want interpolation (inserting a variable's value into the string), you need to use double quotes.
echo '<script type="text/javascript">',
"var lat = ". json_encode($latitude) .";
var lng = ". json_encode($longitude) .";
draw(lat,lng);",
'</script>';
Update: I somehow overlooked the part about json_encode being a PHP call... so the interpolation issue is a moot point, since you just need to concatenate the function's output into the string.
1 Comment
json_encode to the JavaScript string.Functions aren't called inside quoted strings. You need to concatenate it:
echo '<script type="text/javascript">
var lat = ' . json_encode($latitude) . ';
var lng = ' . json_encode($longitude) . ';
draw(lat,lng);
';