how to pass variable from php template to javascript
-
I have a page where I want to display some points on map. I have small templates (like Smarty, but lighter) and there in template I have variable $points, that consists of coordinates of points I need. I need to pass them to javascript (because only javascript can render that map with points). I have 3 variants of doing it. Can you tell, what is best? 1th way: (Template inserting javascript-tags with global variable) tpl.php file: <script> MAP_POINTS = <?php echo json_encode($this->points); ?>; </script> .js file function renderMap(){ var points = MAP_POINTS; // using global. Is it really bad? or who cares? =)) } 2nd way: (Passing variable through the HTML element) tpl.php.file <input type="hidden" value="<?php echo json_encode($this->points); ?>" id="map_points_container"> .js file function renderMap(){ // without globals, but needed to be parsed on local side var points = $.parseJSON ( $( "#map_points_container" ).val() ); } 3rd way: (AJAX-way) I don't pass $this->points from template file at all. I have another .php file that handles all my AJAX requests: Ajaxing.php function get_map_points($params){ // some operations return json_encode ($map_points); } And than on local side I'll have something like this: .js file $.post ( 'ajaxing.php', params, function(points){ renderMap(points); }, 'json'); The third way is usual, but if I already pass some values from template to local page, then I can pass and map points too. In fact, I don't need to make another request for only this map points (that's why I don't like third way) But may be you can advise me another way? a better way? The way I choosed: 1th way with little remarks. All my 'map-rendering' code is in another file and it's like: $(function(){ MAP_APP = {}; MAP_APP.some_prop = null; // some properties MAP_APP.some_method = function(){}; // some methods }); So in template file I only have to extend my MAP_APP object: <script> MAP_APP.points = <?php echo json_encode($this->points); ?>; </script> Yes, global variable. But it's like namespace of whole application. Thanks to everybody.
-
Answer:
The first way is definitely the least complicated and fastest. The second one adds an additional processing step (the parseJSON()) that isn't necessary. The third way is good if you're dealing with lots of data that is optional (i.e. is needed only if the user requests it, and it isn't 100% sure whether that will happen) or dynamic. It creates a new request though, and is not going to be immediately available. If you don't want to use globals, you could e.g. wrap your JavaScript functions into an object, and populate an object property from PHP: <script> MyObject.MAP_POINTS = <?php echo json_encode($this->points); ?>; </script>
Innuendo at Stack Overflow Visit the source
Other answers
There is another funky way of passing variables in a js external file :) Your PHP file: <script type='text/javascript' src='script.js?id=0&some=<?php echo $whatever?>'></script> and inside your script.js you can retrieve those values: var scripts = document.getElementsByTagName('scripts'); // get your current script; for (var i=0,l=scripts.length;i<l;i++){ if(scripts[i].src.indexOf('script.js') !== -1) { // or your script name var query = scripts[i].src.substr(scripts[i].src.indexOf('?')+1); // now you can split the query and access the values you want .... } }
Ibu
The first one is most efficient and fastest. The second one is funky. The third one is also fine. The first because it does not require any other requests. The second one is a bit odd, I would not use that kind of constructs, but that does not mean you can't. The third one is also fine, but you should think about if AJAX is the way to go. If you application requires multiple requests for points for different locations, then it might be the most efficient way to go.
Arend
I would go with your second method since you don't want to use AJAX for it (and it seems odd to use AJAX for something you already have in the current page). You want to limit the number of global variables in your JavaScript because everything in your JavaScript will create an instance of each global variable and thus decrease your performance. I forgot the name of the person, but the man who was heading on optimization at Yahoo! and then went to work for Google gave a lecture about JavaScript optimization, and this was one of his points. EDIT: Found the link: http://sites.google.com/site/io/even-faster-web-sites
Jon
Speed wise 1st way is the best way. But the best way is to create an XML output from PHP and loading that xml into Javascript via Ajax. The best example of this is article given on google maps documentation - http://code.google.com/apis/maps/articles/phpsqlajax_v3.html
Rohit Singh Sengar
Another way: In script_that_defines_renderMap.js: function renderMap(points) { // take "points" as an argument } And then: <script src="script_that_defines_renderMap.js"/> <script> var mapPoints = <?php echo json_encode($this->points); ?>; renderMap(mapPoints); </script> No global variable, no problem.
Jordan
Related Q & A:
- How to pass javascript jQuery variable value in php array?Best solution by Stack Overflow
- How to pass a variable from AlertDialog to an Activity?Best solution by Stack Overflow
- How to pass a javascript object back to the server?Best solution by developer.mozilla.org
- How to input variable inside regex javascript?Best solution by stackoverflow.com
- How to pass the value from the javascript to servlet?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.