Embeding Elixir in JS

Is is possible to write something like this?

<script> console.log(<%= WithDb.Loop.rand_data(5184000, WithDb.Loop.get_pid()) %>) </script>

This grabs JSON encoded data from PostgreSQL to update a chart. Im assuming there is a better way to do this.

So my questions are 3 : 1) is the above possible? 2) is there a better way if so, what? 3) Is there any reason to believe using an /api slug to grab data from the DB is a bad idea?

Thank you!

Hi @NaN, you can send requests from the front-end to the back end, but not like that. Are you using Phoenix or Liveview? Do you want the front end to pull updates, or the back end to push them?

1 Like

You have to use <%= Jason.encode!(WithDb.Loop.rand_data(5184000, WithDb.Loop.get_pid())) %> to convert to a JSON string and on the JS side, use JSON.parse() to convert back to JS Object.

I use this pattern all the time and I don’t have seen any downsides. I didn’t understand the last question, are you taking about creating a separate /api route ?

1 Like

Id like to know how to do both and Id like to learn how to use both Phoenix and LiveView. For this exercise Im using just Phoenix, but if you have a suggestion with LiveView Im happy to learn! Thank you!

<%= WithDb.Loop.rand_data(5184000, WithDb.Loop.get_pid()) %> returns a JSON encoded string using Jason.encode!. How are you using JSON.parse(). Can you give me sample code? Thank you!

I’m using Phoenix LiveView to render out a reader view for markdown. I store the entire edit as a JSON map.


An using a Phoenix Hook load that data into a JS library, I use const chapterContentJson = JSON.parse(this.el.dataset.chapterContentJson); to parse that data into JS.