0

JS & PHP file as follows

console.log(my_val_json);
<script async src="<?php echo get_template_directory_uri(); ?>/js/java.js"></script>
<?php $my_php_val = array( 'banana', 'orange'); ?>
<script type="text/javascript">
  var my_val_json = '<?php echo json_encode($my_php_val); ?>' ;
</script>

Upon refreshing the page multiple times, i get the below error in my console log:

Uncaught ReferenceError: my_val_json is not defined

And sometimes this error also appears on the 1st load. Please advice as i am unable to find any answers online for 2 days now. Thanks!

** NOTE: when i change async to defer, there are no errors (so far) **

DJB
  • 1
  • 1
  • 1
  • Shouldn't it be `var my_val_json = '';`? (note the quotes). – D4V1D Jun 16 '15 at 06:49
  • @D4V1D : Stackoverflow removed it for some reason when i copied and pasted. – DJB Jun 16 '15 at 06:57
  • 2
    php - the space in between. is it a typo? – Vishal Jun 16 '15 at 06:59
  • 1
    What is `java.js` used for? – D4V1D Jun 16 '15 at 07:02
  • @D4V1D : java.js is to write all my Javascripts but sometimes the variables doesnt seem to get the value specified in the PHP and sometime s it does. Currently the entire java.js has the above code "console.log(my_val_json)" – DJB Jun 16 '15 at 07:06
  • @Vishal: Stackoverflow copy and paste error. – DJB Jun 16 '15 at 07:07
  • So you do `console.log(my_val_json);` **before** actually setting `my_val_json` to ``? If so, that is where you error lays. – D4V1D Jun 16 '15 at 07:11
  • try removing the var from 'var my_val_json' once – Vishal Jun 16 '15 at 07:13
  • @D4V1D : Nope. The php file then the js file. But i guess that the js (at times) is loading faster (or from cached) then the php , therefore the error. As stated, when i add "DEFER", the error doesnt appear. But this ultimately defeats the purpose. – DJB Jun 16 '15 at 07:16
  • @Vishal : Nope, didnt work. I tried window.my_val_json as well and same issue. Sometime loads and sometime it doesnt. – DJB Jun 16 '15 at 07:18
  • 1
    see this [http://stackoverflow.com/questions/24227763/using-async-not-working-is-not-defined] – Vishal Jun 16 '15 at 07:23
  • @Vishal: Thanks man! This is the correct solution, but let me try this out first. – DJB Jun 16 '15 at 07:26
  • @DJB: go ahead :) and if it works give that answer an upvote. – Vishal Jun 16 '15 at 07:34
  • @Vishal: The solution is good but it loads the files one after the other, which slows the page load after DOM Loaded. However i tried "window.onload = function () { console.log(my_val_json); }" and so far, there isnt any errors. Keeping my fingers crosses while hitting the F5 repeatedly. – DJB Jun 16 '15 at 07:35

0 Answers0