dev234
Send JavaScript variables from client to server
Hi I have the same issue that this person had here, but I do not think the solution is really relevant to what I am looking for and I don’t understand it that well without context. I tried to ask for clarification there, but I was not able to receive a response.
I just simply need a way to pass a variable from the client-side JS to the server-rendered views/templates.
I did look into this, but that honestly just appears to be above and beyond what I need and I’m wondering if there is a simpler way.
I am using Phoenix LiveView with Surface UI. I am new to elixir/phoenix. Thank you for any help.
Marked As Solved
trisolaran
Add a js hook, and put the logic in the mounted callback of the hook. From there you get the viewport information and push it to the server. mounted callback is executed on the client after the LV has completed mounting.
Also Liked
mpope
It depends on how complex your use-case is. If you need the Javascript variable to go through any logic on the server, then checkout LiveView Javascript Hooks, which work very well and you can create GenServer-like LiveControllers that react to client events. Most of the boilerplate is already setup in the included LiveView javascript.
However, if you simply want to display the values then the server can render an empty div with a specific id (tag) and the client-side JS can then use getElemementByTagName and set the value setting the innerHTML on the returned element.
benwilson512
https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#push_event/3
This is the function that exists for pushing a message to JS.
trisolaran
this should be handle_event("test_event", %{"data" => your_data}, socket)
benwilson512
Can you elaborate about why hooks are a poor fit?
dev234
That’s what I figured, thank you again everyone for all of your help







