Tutorial :getting a variable value in an html page and using it in an external js



Question:

hi have a php template that displays an html page. in it there is a call to a js file that initializes some jquery plugins.

on the template i have this code:

(function($) {      $(document).ready(function(){       var adlow = <?php echo $jSeblod->disparities_tick_lower->value ?>;       var adhigh = <?php echo $jSeblod->disparities_tick_upper->value ?>;       var adtickno = <?php echo $jSeblod->disparities_tick_divisions->value ?>;        });  })(jQuery);  

then on the init.js page i call adlow, adhigh and adtickno. i get variable undefined errors.

the php is returning the correct values. but then the external init file is not getting them. do i need to do something special to get the init file to be able to use these variables? all i did was just plug them in...

thanks, i am a little hazy on the interaction between these pages.


Solution:1

They need to be globals for other pages to use them. Try removing the var. Or namespace them, which is better practice:

$(document).ready(function(){      MYAPP = {};      MYAPP.adlow = <?php echo $jSeblod->disparities_tick_lower->value ?>;      MYAPP.adhigh = <?php echo $jSeblod->disparities_tick_upper->value ?>;      MYAPP.adtickno = <?php echo $jSeblod->disparities_tick_divisions->value ?>;       });  


Solution:2

You need to print them in global scope before init.js get loaded.

<script>      var adlow = <?php echo $jSeblod->disparities_tick_lower->value ?>;      var adhigh = <?php echo $jSeblod->disparities_tick_upper->value ?>;      var adtickno = <?php echo $jSeblod->disparities_tick_divisions->value ?>;  </script>  <script src="init.js"></script>  

Printing them during $(document).ready() makes no sense. The init.js already get loaded before that.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »