Passing database information to a block's javascript.

Permalink
Concerning block development, there is times I need my block to execute javascript that would contain data stored via the db.xml.

So for example, I have my block accepting a number and storing it in the database. Then in my javascript, I need to use that variable. I can just use inline javascript fairly easy, and do a script tag in the view.php, and use the php variables inline. But what happens when I need my javascript to load itself in the footer instead of inline, because it has a jquery dependency for example. Loading it inline will not work because it loads before jquery. I could just load my jquery in the head, but its not guaranteed that every template does this. So if I package my block for the marketplace, the javascript may not work on all templates because its inline. I know how to require an asset and have it load in the footer. My problem is, how do I pass php data to the required javascript assets? Or how have others tackled this problem in the past?

ob7dev
 
JohntheFish replied on at Permalink Best Answer Reply
JohntheFish
Option 1.
Convert the data to json, escape it with h(), then print it into a data attribute of a tag in the block html.
Your script in the footer can then (in a ready handler) search for the data attribute, read it, parse the json, and have all the data to work with.

Option 2.
Add it to the footer using add footer item in the block controller.

Option 3.
Use an ajax callback to read json data from the server.

Unless you need option 3 for dynamically changing data, option 1 is likely the easiest to get your head round and involves less network traffic. Option 2 is also fairly straight forward and may be better for big data.

There are other ways, but those are my top 3.
ob7dev replied on at Permalink Reply
ob7dev
Genius idea about using the data attributes.
MrKDilkington replied on at Permalink Reply
MrKDilkington
Hi ob7dev,

As a side note.
"I could just load my jquery in the head, but its not guaranteed that every template does this. So if I package my block for the marketplace, the javascript may not work on all templates because its inline."

In general, jQuery is required to be loaded in the page head. If it isn't it will break some core blocks.
ob7dev replied on at Permalink Reply
ob7dev
I'm not sure exactly how option 2 would work. How would I pass php variables to javascript via add to footer? I need to do this in a package that doesn't use blocks therefore no dom element to pass the data to via a data attribute. I can only add footer items that are javascript or css, so how would I add a footer item that contains the php variables contents?
ob7dev replied on at Permalink Reply
ob7dev