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

blackode
Elixir Upgrading is so Simple in Ubuntu and It worked for me Ubuntu 16.04 git clone https://github.com/elixir-lang/elixir.git cd elixir...
New
owaisqayum
I have a sample string sentence = "Hello, world ... 123 *** ^%&amp;*())^% %%:&gt;" From this string, I want to only keep the integers, ...
New
lorenzo
Hey everone! I created a prototype for my app using Nodejs for the api. But the framework I chose wasnt great (in general theresnt any g...
New
crispinb
On reading dhh’s latest The One Person Framework it strikes me that Phoenix with LiveView is already pretty much this. However, never hav...
New
Crowdhailer
I’ve been hearing much about the new formatter and it’s something I have been keen to try. I find examples buy far the most illuminating...
248 19204 150
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
New
PragTob
Hey everyone, this has been on my mind for some time and I’d love your input on it! TLDR: I feel like maps are superioer for storing and...
New
Qqwy
I would like to spark a discussion about the static access operator: .. For whom does not know: it is used in Elixir to access fields of...
New
jesse
Hi everyone, I hesitated to post this here because I don’t want you to think I’m spamming, but I’ve been working on a Platform-as-a-Serv...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement