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 Responses

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

vans163
So useless benchmarks aside, Its possible to write a webserver that can serve 300k requests per second (perhaps more with optimizations)....
New
cvkmohan
The upcoming Phoenix 1.6 release looks very interesting. Became a habit to watch the commits - and - what they are bringing in. phx.gen...
New
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
pillaiindu
In django there is a cache framework backed by memcached. Rails also puts a lot of emphasis on caching, and even the idea of russian-doll...
New
chuck
Let me start by stating an assumption: Phoenix is a great approach to building REST APIs. There are many reasons for this, but I will ass...
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
Ankhers
Just a little information upfront. Generally speaking, if I feel like I need to either break a pipe chain or use an anonymous function in...
New
marciol
Please, let me know if this kind of discussion already took place in another topic . Hi all, how do you consider if is better to build ...
New
rower687
Hi all, I’ve been reading a lot about the “let it crash” term and how supervising processes and the whole messaging passing make an elixi...
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

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
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
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement