I have a page where I want to display some points on the map. I have small templates (e.g. Smarty, but lighter), and there in the template I have $ points variables that consist of the coordinates of the points I need. I need to pass them to javascript (because only javascript can display this map with dots).
I have 3 options for this. Can you say which is better?
1st method: (Template inserting javascript tags with a global variable)
Tpl.php file:
<script> MAP_POINTS = <?php echo json_encode($this->points); ?>; </script>
.js file
function renderMap(){ var points = MAP_POINTS;
Second way: (Passing a variable through an HTML element)
tpl.php.file
<input type="hidden" value="<?php echo json_encode($this->points); ?>" id="map_points_container">
.js file
function renderMap(){
Third Way: (AJAX-way)
I do not pass $this->points
from the template file at all. I have another .php file that handles all my AJAX requests:
Ajaxing.php
function get_map_points($params){
And than on the local side I will have something like this:
.js file
$.post ( 'ajaxing.php', params, function(points){ renderMap(points); }, 'json');
The third way is the usual one, but if I already transfer some values โโfrom the template to the local page, then I can transfer and plot the map points. In fact, I do not need to make another request only for these points on the map (why I do not like the third way)
But maybe you can advise me another way? The best way?
As i chose:
1st method with a few comments. All my "map rendering" code is in another file, and it looks like this:
$(function(){ MAP_APP = {}; MAP_APP.some_prop = null;
Therefore, in the template file, I need to expand the MAP_APP object:
<script> MAP_APP.points = <?php echo json_encode($this->points); ?>; </script>
Yes, a global variable. But this is similar to the namespace of the entire application.
Thanks to everyone.