I am trying to call JavaScript function with parameter that are PHP variables. I have tried 2 approaches.
calling JavaScript function in PHP with script tag
Use json_encode(). If you don't there will always be the possibility you escaped your data incorrectly as it passes from the PHP to the HTML/JS layer.
$vars = array($lat, $lang, $zoom);
// JSON_HEX_TAG and JSON_HEX_AMP are to remove all possible surprises that could be
// caused by vars that contain '' or '&' in them. The rules for
// escaping/encoding inside script elements are complex and vary depending
// on how the document is parsed.
$jsvars = json_encode($vars, JSON_HEX_TAG | JSON_HEX_AMP);
echo "";
In general, for your sanity, all data that is in PHP that you need to make available to js running on the current page should be collected into a single PHP array and then placed into a single js object. For example:
array(
'lat' => $lat,
'lang' => $lang,
'zoom' => $zoom
),
'username' => $username,
'some_other_data' => $more stuff
);
?>
Now there is only a single point of contact between the JS and PHP/HTML layers so you can easily keep track of what you are putting into the JS namespace.