WFransen

WFransen

Best practice use data in javascript (thus passing data)

Haven’t found a topic on the elixir forum regarding this, only on stackoverflow. If it exists already, please point me in the right direction and I’ll delete this post. Because the response was limited, I was wondering if the Phoenix experts here could provide their opinions regarding passing data from the controller to your JS.

A use case that I’m facing now:
Building a timeline-ish feature with an edit page. On the edit page, i want to let the user upload images asynchronously. (so that if they edit something in the text field, the explanation on the timeline, and then upload an image it doesn’t need to refresh) But I need the article id to make the asynchronous call.

As far as i know there are 2 options:

  • work with data attributes (link)
  • put a tag in your template, and assign a variable where you put your json encoded (elixir) variable so that you can access it in your javascript.

This is a problem with multiple frameworks, and I’d be truly happy if some sort of best-practice could be formed.

Thank you in advance!

Most Liked

kokolegorille

kokolegorille

I prefer to pass data to js with data attributes, it’s easy.

I have something like this in my template

<div 
  id="app" 
  data-src="<%= display_path @picture, :large %>"
  data-id="<%= @picture.id %>"
  data-token="<%= @token %>"></div>

and I retrieve like this in app.js.

const root = document.getElementById('app');
if (root) {
  const { src, id, token } = root.dataset;
  console.log(src, id, token);
}
kokolegorille

kokolegorille

Hello and welcome,

It is a little bit more complicate to pass js data to the server, because http is not bidirectional.

Are You sure You cannot do all client side? recently I had to display datetime in the browser timezone. It was simpler to add some class to datetime container (“utc_to_local”) and make the change client side only.

But if You want to make it server side, I think the easiest solution would be to pass the locale, like new?locale=whatever. Because new is a get request.

You could use a plug to set a session_id.

This way, You could pass data to the server with this session_id, and retrieve this data server side

It’s not even needed, and it is nice to see how it is done in liveview, which use websocket under the hood. You can set params to the socket, and retrieve them in liveview.

let liveSocket = new LiveSocket("/live", Socket, {
  params: {
    _csrf_token: csrfToken,
    locale: Intl.NumberFormat().resolvedOptions().locale,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    timezone_offset: -(new Date().getTimezoneOffset() / 60),
  }
});

# In liveview mount

    if connected?(socket) do
      Logger.info("SOCKET PARAMS: #{inspect get_connect_params(socket)}")
    end

# And the result

  [info] SOCKET PARAMS: %{
    "_csrf_token" => "...",
    "_mounts" => 0,
    "_track_static" => ["..."],
    "locale" => "fr",
    "timezone" => "Europe/Zurich",
    "timezone_offset" => 2
  }

So You could use websocket, but it does not seems You need this, You just want to localize your login form. => new?locale=whatever and retrieve the locale server side.

Use an id to the new link, and add locale params to the path of this link with js.

KP123

KP123

It’s not magic it’s part of the browser spec. My point being that it’s not Phoenix specific.

Where Next?

Popular in Discussions Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
ejpcmac
I have discovered Nix last month and I am currently on my way to migrating to it—both on macOS at home and the full NixOS distrubution at...
New
Markusxmr
Since Drab has been developed for a while in the open, introducing the Liveview functionality in a way it happend appears to undermine th...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
Owens
Hello all, I am developing a new mobile app with Flutter frontend and Phoenix backend. The mobile app has real-time task management and c...
New
opsb
We’re considering our architecture from a viewpoint of scaling our traffic heavily over the next 6 months. Our current deployment is runn...
New
cblavier
Hey there, It’s been more than a year since we started using LiveView as our main UI library and building a whole library of UI componen...
New
fireproofsocks
I’ve been working on an Elixir project that has required a lot of scripting. I usually reach for Elixir because I like it more (and in th...
New
matthias_toepp
I’d love to hear what people think about Wisp, the new Gleam web framework started by Gleam’s primary creator Louis Pilfold. Gleam, alon...
New

Other popular topics Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New

We're in Beta

About us Mission Statement