How can I fire an HTTP request from a Phoenix component on-click?

I have a basic phoenix view which has a button. I want this button to fire a post request when clicking on it.

Also I have another component which should trigger a redirection on click and I also don’t know how to do that.

I can only find answers about how to fire an event from a live view… but I am not using a live view, I just want to make a regular HTTP request on click.

Is there a way to do this without having to write the JS by hand?

Thanks!

Have you tried creating a form and a post route where you can submit the action and do the work you want on the server side?

I would use Req for HTTP requests, version 1:

# in your liveview
def render(assigns) do
    <button  phx-click="submit"/>
end

def handle_event("submit", _value, socket) do
  # HTTP request
  {:ok, _res} = Req.post!("")
  {:noreply, socket}
end

Version 2 would handle HTTP request in async function.

I think this will have to be the way, I just didn’t want to deal with forms since they don’t really make sense on this use case (I just want to trigger an action on the server by clicking a button, the POST request won’t have a body)

This would work if I was using LiveView but since this is a super simple page with just some buttons that send HTTP requests I think making it a liveview with a long living websocket sonnection would be overkill

You should be able to use the Link component with method="post".

i.e. <.link href={...} method="post" ...>...</.link>

The link is to the LiveView docs but the <.link/> component should work in dead views as well.

1 Like