1

This question already has an answer here:

I've been stuck on this all day and I haven't been able to find an answer that solved my issue:

I need to make a PHP variable available in my Javascript file. Currently I'm using a fetchMarkers.php to retreive records from my database, and I would like to make this info available (they're arrays) in my javascript file.

How can I get this to work? I'm currently working with the PHP in my page--front.tpl.php file because I'm unsure of how to call it.

But, my question for now is: How do I make PHP Arrays available to my Javascript file? I've json_encode()d my arrays in the PHP with:

    echo json_encode($latitudes);
    echo json_encode($ar);

And I've tried multiple things but none of them worked (so many things that it just got me more and more confused). So therefor my question is just:

How can I access these two variables in my Javascript?

marked as duplicate by kiamlaluno Apr 6 '15 at 3:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • You should check out how to build a module first. This is not a good way of working with Drupal 7. If I'm reading it correctly, you're connecting to the database from the tpl file. You should only make connections from a module. – Maarten De Block Apr 5 '15 at 18:00
  • I've put the code inside a .module file now, and with a test it successfully prints out the array on the page ('ve set up a special area for any developing test). But still, how do I make the arrays I created in my .module file globally available? – Kay Angevare Apr 5 '15 at 19:49
2

You don't need to manually convert PHP array to JSON object; adding a drupal setting will do this for you.

$vars = array('variableName' => 'value');
drupal_add_js($vars, 'setting');

If you want to understand in detail, like how to use it with Drupal Behaviors. See my answer on https://drupal.stackexchange.com/a/74535/17883

  • What should the value of 'setting' be? – Kay Angevare Apr 5 '15 at 18:24
  • it needs to be 'setting' only :) see my previous answer. I just added a link. – Himanshu Pathak Apr 5 '15 at 18:26
0

There are multiple ways to pass data to JS. Printing JSON encodings in a template file is not a good method.

I recommend Maarten's suggestion at employing a module. Once you've built a module, checkout the documentation on the JS API, specifically the settings section if you're looking to pass module variables to JS.

If you're looking to grab content data (e.g. your nodes have custom geo coordinate fields). You might want to look at the services module; it will let you grab content data in AJAX requests.

Not the answer you're looking for? Browse other questions tagged or ask your own question.