Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to pass data from Phoenix to Javascript

I see 3 ways of doing this.

  1. Using <%= %> inside <script> in *.html.eex
  2. Use channels to pass data to Javascript
  3. Build a json api

#1 seems the easiest but I couldn't find or think of a good way to do it yet.

Note: real-time update is not my requirement.

like image 397
Charles Han Avatar asked Aug 20 '16 08:08

Charles Han


People also ask

Does Phoenix LiveView use JavaScript?

No JavaScript. You don't need any JavaScript to build web applications with LiveView.

How do I pass data from one page to another in JavaScript?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.


1 Answers

(2) is not a good idea if you don't want real time updates. (3) may be too unnecessarily complicated if you don't want to load the data using AJAX. You should use (1) if you just need some data to be accessible from JS and don't want to change it without a whole page reload.

Since valid JSON is also valid JS, you can just use Poison.encode!(). If your data is in @posts, you can do this in *.html.eex:

<script>
  var POSTS = <%= Poison.encode!(@posts) %>;
</script>

and then load other JS after this and access the posts using the global POSTS variable. (You might want to namespace it into something like App.posts = ...:

<script>
  var App = window.App || {};
  App.posts = <%= Poison.encode!(@posts) %>;
</script>

Make sure @posts only contains data that can be converted to JSON (no tuples) and only has the fields that the user is allowed to see.

like image 177
Dogbert Avatar answered Oct 21 '22 07:10

Dogbert